HttpClient总是无限卡死

public String getContent(String url, int timeOut) {
        HttpClientBuilder httpBuilder = HttpClientBuilder.create();
        if (timeOut > 0) {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
            httpBuilder.setDefaultRequestConfig(requestConfig);
        }
 
        CloseableHttpClient closeableHttp = httpBuilder.build();
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = closeableHttp.execute(request);
 
            HttpEntity entity = response.getEntity();
 
            return entity == null ? null : EntityUtils.toString(entity, CharacterSet.UTF8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (request != null) {
                    request.abort();
                }
 
                if (response != null) {
                    response.close();
                }
 
                closeableHttp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

   

 

   

   EntityUtils.consume(entity);

response.close();

 

在HttpClient 4.0+的版本,正确的关闭连接如下:

 

  1. EntityUtils.consumeQuietly(response.getEntity());  


记得这个最好放在finally块中。

 

 

在HttpClient 3.0+版本中,正确的关闭如下:

 

  1. private static void close(HttpMethod method) {  
  2.     if (method != null) {  
  3.         method.releaseConnection();  
  4.     }  
  5. }  

 

https://www.oschina.net/question/2298861_240814?sort=default&p=1#answers

http://blog.csdn.net/wxyfighting/article/details/9075051

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值