HttpURLConnection 协议 -包含代理判断

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

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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值