I am using HttpClient within a servlet to make calls to a resource which I return as the servlets response after some manipulation.
My HttpClient uses PoolingHttpClientConnectionManager.
I create the client like so:
private CloseableHttpClient getConfiguredHttpClient(){
return HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
.setConnectionManagerShared(true)
.setConnectionManager(connManager)
.build();
}
I use this client within a Try With Resource within the servlets service method, so it is auto closed. To stop the the connection manager from being closed, I set setConnectionManagerShared
to true.
I have seen other code samples that do not close the HttpClient. Should I not be closing this resource?
Thanks
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself.
Overview Apache HttpClient is a popular Java library providing efficient and feature-rich packages implementing the client-side of the most recent HTTP standards. The library is designed for extension while providing robust support for the base HTTP methods.
shutdownNow(); client = null; System. gc();
For httpcomponents version 4.5.x:
I found that you really need to close the resource as shown in the documentation: https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
} finally {
response1.close();
}
For other versions of httpcomponents, see other answers.
For older versions of httpcomponents (http://hc.apache.org/httpcomponents-client-4.2.x/quickstart.html):
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution.
Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
GetMethod httpget = new GetMethod("http://www.url.com/");
try {
httpclient.executeMethod(httpget);
Reader reader = new InputStreamReader(httpget.getResponseBodyAsStream(), httpget.getResponseCharSet());
// consume the response entity and do something awesome
} finally {
httpget.releaseConnection();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With