Search code examples
javaapache-httpclient-4.xtry-with-resources

Using CloseableHttpClient with try-with-resources


I've been searching for a completed example of CloseableHttpClient with try-with-resources. I am confused on if closing CloseableHttpClient also closes the CloseableHttpResponse object that will be created when I call httpclient.execute(post). Do I need to wrap CloseableHttpResponse in a try-with-resources too?

Example:

try(CloseableHttpClient httpclient = HttpClients.custom().build()) {
    HttpPost post = new HttpPost(url);
    CloseableHttpResponse res = httpclient.execute(post);

    // do something with res
} catch (Throwable e) {
    // do something with error
}

Solution

  • If you want for the reponse to take part in the try-with-resource you do. Although as you catch the Exceptions already, you can end with } - no additional catch required.

    Technically it's not a requirement as the implementation for close () in CloseableHttpResponse is empty

    You need to close CloseableHttpResponse to release the resources, as per httpcomponents documentation (https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html)

    Oh. Don't catch Throwable - this is bad style and can cause really hard to find errors.