Search code examples
javaservletshttpclient

Proper usage of Apache HttpClient and when to close it.


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


Solution

  • 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();
      }