HttpUrlConnection使用之后是否需要disconnet()

📁 365体育投注365bet 📅 2025-09-25 11:24:57 👤 admin 👁️ 9131 ❤️ 154
HttpUrlConnection使用之后是否需要disconnet()

现在用的最多的都是http连接池,看其他帖子连接池性能更好些,老代码中jdk原生的http请求出问题时也是需要定位修复的,

一个比较原生和请求池性能的帖子:https://blog.csdn.net/u011479540/article/details/51918474

1.如果代码没有什么异常在获取使用完流之后,关闭流,http连接会自动被关闭

2.如果http连接超时,或者读取数据连接socket超时,没有获取到流,此时需要主动关闭http(disconnet())

总结:

如果使用了HttpUrlConnection进行http请求,

1.最好在finally中加disconnet(),以防异常时候http连接未被关闭,造成tcp连接堆积

2.并且要设置连接和读取超时时间,否则程序会一直卡在获取流这一步

(记一次生产事故,因为是新人需要维护之前的老代码,所以很多小坑小洼难免不易发现,如下代码原未设置超时时间及断连,在某个下层应用提供url有问题后,http连接出问题,从早晨开始陆续有商户反应支付请求变慢,因为服务运行半年平稳无事故,开始以为是公司网络受到攻击,后续通过分析日志发现是此url请求不通未做处理导致程序卡顿,tcp连接堆积,服务器只有5M带宽,网络就变慢了!!!)

import java.net.HttpURLConnection;

public static String sendGET(String getAccessTokenUrl){

StringBuffer openJsonStr = new StringBuffer();

InputStream inputStream = null;

BufferedReader in =null;

HttpURLConnection httpURLConnection =null;

try {

httpURLConnection = HttpClientUtil.getHttpURLConnection(getAccessTokenUrl);

httpURLConnection.setConnectTimeout(30000); // 设置连接主机超时(单位:毫秒) 开始未设置

httpURLConnection.setReadTimeout(30000); // 设置从主机读取数据超时(单位:毫秒) 开始未设置

inputStream = httpURLConnection.getInputStream();

in = new BufferedReader(new InputStreamReader(inputStream, Constant.DEFAULT_CHARSET));

String lines="";

while((lines = in.readLine()) != null){

openJsonStr.append(lines);

}

} catch (IOException e) {

log.error(e.getMessage());

}catch (Exception e) {

log.error(e.getMessage());

}

finally{

if(in!=null){

try {

in.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(inputStream!=null){

try {

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (httpURLConnection != null) {

try {

httpURLConnection.disconnect(); // 开始未设置

} catch (Exception e) {

e.printStackTrace();

}

}

}

return openJsonStr.toString();

}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration

@ContextConfiguration(locations = {“classpath:spring.xml”, “classpath:spring-mybatis.xml”, “classpath:spring-redis.xml”, “classpath:spring-face.xml”})

@ActiveProfiles(“test”)

public class AndroidFaceTest {

@Test

public void testGetHttp(){

PayHelper.sendGET(“http://39.106.131.159/add.php”);

}

}

相关推荐