为什么httpclient老是卡住

最近在修改快门下载功能时,发现同一文件只能下载成功2次,此后再点下载就没反应了。

我的httpclient是如下方式创建的,使用了连接池。

private static CloseableHttpClient httpclient = HttpClientBuilder.create().build();

我的调用方式如下:

public static byte[] executeQuery(String url, String chartSet) throws ClientProtocolException, IOException {
        if (StringUtil.isBlank(chartSet)) {
            chartSet = "UTF-8";
        }
        byte[] bytes = null;
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
		InputStream instream = entity.getContent();
		bytes = FileUtil.readAsByteArray(instream); 
        }
        return bytes;
}

尝试几次后发现,下载成功的次数和maxConnPerRoute相同,该参数默认值就是2,并且可以采用以下方式修改:

private static CloseableHttpClient httpclient = HttpClientBuilder.create().setMaxConPerRoute(5).build();

于是,我怀疑是连接没有释放。但我又不可能调用httpclient.close(),否则连接池就失效了。

最终发现,错误原因是我既没有释放instream,也没有释放httpget(http://www.oschina.net/question/925814_131284)。

那么,可以通过释放instream或httpget的方法来解决。

方案一:释放instream

public static byte[] executeQuery(String url, String chartSet) throws ClientProtocolException, IOException {
        if (StringUtil.isBlank(chartSet)) {
            chartSet = "UTF-8";
        }
        byte[] bytes = null;
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
		InputStream instream = entity.getContent();
		bytes = FileUtil.readAsByteArray(instream); 
                // Closing the input stream will trigger connection release
                instream.close();
        }
	return bytes;
}

方案二:释放httpget

public static byte[] executeQuery(String url, String chartSet) throws ClientProtocolException, IOException {
        if (StringUtil.isBlank(chartSet)) {
            chartSet = "UTF-8";
        }
        byte[] bytes = null;
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
		InputStream instream = entity.getContent();
		bytes = FileUtil.readAsByteArray(instream); 
        }
	// release links
	httpget.releaseConnection();
	return bytes;
}



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值