Http发送请求并回执json 输出

直接源码

package nc.bs.fdgyl.alert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import nc.bs.logging.Logger;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

public class HttpGetTest {

	public static void main(String[] args) {
		String httpURL = "http://ip:port/ww/hel?use=demo&psw=111111";
		JSONObject json = sendHttpRequest(httpURL);
		System.out.println(json.size());
	}

	/**
	 * 发送请求
	 * 
	 * @param httpURL
	 * @return
	 */
	public static JSONObject sendHttpRequest(String httpURL) {
		HttpURLConnection curconnection = null;
		JSONObject result = null;
		try {
			String requestMethod = "GET";// 请求方式
			String contentType = "application/json;charset=utf-8";
			curconnection = getConnection(httpURL, requestMethod, contentType);
			result = receiveResponseJSON(curconnection);
		} catch (Exception e) {
			Logger.debug(e.getStackTrace());
		} finally {
			if (curconnection != null)
				curconnection.disconnect();
		}
		return result;
	}

	/**
	 * 获得连接
	 * 
	 * @param httpURL
	 * @param requestMethod
	 * @param contentType
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection getConnection(String httpURL,
			String requestMethod, String contentType) throws IOException {
		HttpURLConnection connection = null;
		URL url = null;
		try {
			url = new URL(httpURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput("GET".equals(requestMethod) ? false : true);// post请求
																				// 则为true
			connection.setRequestProperty("Content-type", contentType);
			connection.setRequestMethod(requestMethod);// POST或GET
		} catch (IOException e) {
			throw new IOException("在获取连接中出错:" + e.getMessage());
		}
		return connection;
	}

	/**
	 * 解析链接
	 * 
	 * @param connection
	 * @return
	 * @throws Exception
	 */
	public static JSONObject receiveResponseJSON(HttpURLConnection connection)
			throws Exception {
		try {
			InputStream input = connection.getInputStream();
			String result = IOUtils.toString(input, "UTF-8");
			URLDecoder decoder = new URLDecoder();  
			String decode = decoder.decode(result, "UTF-8");
			return JSONObject.fromObject(decode);
		} catch (Exception e) {
			throw new Exception("读回执时出错:", e);
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值