Correct use of Apache HttpClient and when to close it.

I am using HttpClient inside a servlet to make calls to a resource, which I return as a response from the servlet after some manipulation.

My HttpClient is using PoolingHttpClientConnectionManager.

I create a client like this:

private CloseableHttpClient getConfiguredHttpClient(){
    return HttpClientBuilder
        .create()
        .setDefaultRequestConfig(config)
        .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
        .setConnectionManagerShared(true)
        .setConnectionManager(connManager)
        .build();
}

      

I'm using this client as part of a Try With Resource in a servlet service method, so it's automatically closed. To stop the connection manager, I set it setConnectionManagerShared

to true.

I have seen other code examples that do not close the HttpClient. Should I not close this resource?

thank

+3


source to share


2 answers


However, you don't need to explicitly close the HttpClient (you may already be doing this, but it's worth noting), you need to make sure the connections are released after the method is executed.

Edit: The ClientConnectionManager in the HttpClient will be responsible for maintaining the state of the 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();
  } 

      

+1


source


I found that you actually need to close the resource as shown in the documentation: https://hc.apache.org/httpcomponents-client-ga/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();
}

      

+1


source







All Articles