Bri Veillette Bri Veillette - 6 months ago 74
Java Question

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
}

Jan Jan
Answer

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

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