HttpURLConnection 协议
/**
* 仅仅在发送url的时候调用
* @param url
* @return
*/
public String sendHttpURLConnection(String url){
//logger.info("向微信发起请求,发送的url为:"+url);
String str = "";
try {
URL getUrl = new URL(url);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
HttpURLConnection connection;
//代理判断,0-不使用代理;1-使用代理
if("0".equals(ServicePort_shezhi)){
connection = (HttpURLConnection) getUrl.openConnection();
}else{
Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress(proxyHost, Integer.valueOf(proxyPort)));
connection =(HttpURLConnection)getUrl.openConnection(proxy);
}
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
connection.setConnectTimeout(25000);
connection.setReadTimeout(25000);
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String lines;
//获取返回的字符流转化为字符串
while ((lines = reader.readLine()) != null) {
str = str + lines;
}
reader.close();
// 断开连接
connection.disconnect();
//logger.info("向微信发起请求,微信返回的字符串为:"+str);
return str;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("向微信发起请求出现异常,微信返回的字符串为:"+str+" e.getMessage()="+e.getMessage());
//logger.info("向微信发起请求出现异常,微信返回的字符串为:"+str,e.getMessage());
}
//运行到此说明发生错误
str="errcode";
return str;
}

本文介绍了一个使用 HttpURLConnection 发送 HTTP 请求的 Java 示例代码。该方法通过指定 URL 连接到远程服务器并读取响应,支持代理设置及超时配置。
3511

被折叠的 条评论
为什么被折叠?



