/**
* send http request
*/
public static JSONObject sendGet(URL url){
String result = "";
BufferedReader in = null;
JSONObject jsonObject = null;
try {
HttpURLConnection oConn = null;
if(Config.USE_PROXY){
Proxy oProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Config.PROXY_ADDR, Config.PROXY_PORT));
oConn = (HttpURLConnection) url.openConnection(oProxy);
}else{
oConn = (HttpURLConnection) url.openConnection();
}
oConn.setConnectTimeout(5000);
oConn.connect();
if(oConn.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(oConn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}
jsonObject = new JSONObject(result);
} catch (Exception e) {
System.err.println(url.toString()+"---get fail!");
e.printStackTrace();
jsonObject = null;
}finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return jsonObject;
}
上面的例子将请求返回的数据转化成了json格式,Config.USE_PROXY判断是否需要设置代理。
Java发送HTTP请求
最新推荐文章于 2023-01-04 09:52:08 发布