使用httpclient4出现ConnectionPoolTimeoutException: Timeout waiting for connection异常

背景:今天有个需求是在发布之前检查一下模板中引用的静态资源是否被发布,然后用正则取出被引用的静态资源的url,然后用httpclient去请求,看返回码是否是404,如果是404,则表明这个静态资源是不存在的,即有问题,该模板不能发布。

验证的核心代码如下:

if (urls.size() > 0) {
            HttpClient httpClient = null;
            try {
                httpClient = SimpleHttpsTrustClientTemplate.createHttpClient();
                HttpGet httpGet = new HttpGet();
                HttpResponse response = null;
                for (Iterator<String> iter = urls.iterator(); iter.hasNext();) {
                    httpGet.setURI(URI.create(iter.next()));
                    response = httpClient.execute(httpGet);
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
                        iter.remove();
                    }
                }
            } catch (Exception e) {
                LOGGER.error(e);
            }
        }

 测试就出现了“ConnectionPoolTimeoutException: Timeout waiting for connection”异常,应该是说连接没有释放,后来查看API,发现没有直接释放连接的方法,后来查了一下httpclient4中文版帮助文档(http://www.docin.com/p-564016244.html),说是要将响应流的内容消耗掉就会关闭连接,于是加了一行response.getEntity().getContent().close();重试,发现问题得以解决。

完整代码如下:

if (urls.size() > 0) {
            HttpClient httpClient = null;
            httpClient = SimpleHttpsTrustClientTemplate.createHttpClient();
            HttpGet httpGet = new HttpGet();
            HttpResponse response = null;
            for (Iterator<String> iter = urls.iterator(); iter.hasNext();) {
                httpGet.setURI(URI.create(iter.next()));
                try {
                    response = httpClient.execute(httpGet);
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
                        iter.remove();
                    }
                } catch (ClientProtocolException e) {
                    LOGGER.error(e);
                } catch (IOException e) {
                    LOGGER.error(e);
                } finally {
                    try {
                        if (response != null) {
                            response.getEntity().getContent().close();
                        }
                    } catch (IllegalStateException e) {
                        LOGGER.error(e);
                    } catch (IOException e) {
                        LOGGER.error(e);
                    }
                }
            }
        }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值