I am using Apache PoolingHttpClientConnectionManager
to pool the connections along with ClosableHttpClient
and CloseableHttpResponse
to make the service call. To read the sever response I am using EntityUtils.consume(httpResponse.getEntity())
. I would like to know how to release the connection when httpResponse
becomes null
. I have tried releaseConnection()
(method of PoolingHttpClientConnectionManager
) but it is not working. You can find the code below.
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();
}
CloseableHttpClient
should not return a null response. On errors should raise an exception, so its safe to callclose()
. See documentationDo not call
EntityUtils.consume(httpResponse.getEntity());
infinally
clause because if error occurs theclose
method won't be executedPlease read connection eviction policy in http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html you can implement a monitor to close expired and idle connections that have been blocked or closed on server. The monitor calls
closeExpiredConnections()
andcloseIdleConnections(period