直接源码
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);
}
}
}