我正在使用Apache PoolingHttpClientConnectionManager
与ClosableHttpClient
和CloseableHttpResponse
一起汇集连接以进行服务调用。要阅读服务器响应,我正在使用EntityUtils.consume(httpResponse.getEntity())
。我想知道在httpResponse
成为null
时如何释放连接。我尝试了releaseConnection()
(PoolingHttpClientConnectionManager
的方法),但它不起作用。你可以在下面找到代码。
String decision = "";
CloseableHttpResponse httpResponse = null;
try {
HttpPost requestPost = new HttpPost(endpoint1); requestPost.setHeader("Connection", "close");
requestPost.setHeader("Content-type",
"application/x-www-form-urlencoded");
requestPost.addHeader("Accept-Encoding", "gzip,deflate");
String xmlRequestStr = "Request=" + URLEncoder.encode(urlString);
String soRequest = xmlRequestStr;
requestPost.setEntity(new StringEntity(soRequest));
httpResponse = client.execute(requestPost);
decision = EntityUtils.toString(httpResponse.getEntity(),encod);
//connEvictor.shutdown();
} catch (Exception e) {
System.out.println("Pooling Connection manager Exception : " + e.getMessage());
e.printStackTrace();
//connEvictor.shutdown();
throw new ToolkitException("Connection Manager Exception", e.getMessage());
} finally {
EntityUtils.consume(httpResponse.getEntity());
httpResponse.close();
}
答案 0 :(得分:0)
CloseableHttpClient
不应返回null响应。关于错误应引发异常,因此可以安全地调用close()
。见documentation
请勿在{{1}}子句中调用EntityUtils.consume(httpResponse.getEntity());
,因为如果发生错误,则不会执行finally
方法
请阅读http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html中的连接驱逐策略,您可以实施监视器以关闭已在服务器上阻止或关闭的过期和空闲连接。监视器调用close
和closeExpiredConnections()