为什么httpclient老是卡住

来源:互联网 发布:路由器上面的访客网络 编辑:程序博客网 时间:2024/06/09 21:06

最近在修改快门下载功能时,发现同一文件只能下载成功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 linkshttpget.releaseConnection();return bytes;}



0 0
原创粉丝点击