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+的版本,正确的关闭连接如下:
- EntityUtils.consumeQuietly(response.getEntity());
在HttpClient 3.0+版本中,正确的关闭如下:
- private static void close(HttpMethod method) {
- if (method != null) {
- method.releaseConnection();
- }
- }
https://www.oschina.net/question/2298861_240814?sort=default&p=1#answers
http://blog.csdn.net/wxyfighting/article/details/9075051