Bri Veillette Bri Veillette - 1 year ago 341
Java Question

Using CloseableHttpClient with try-with-resources

I've been searching for a completed example of

with try-with-resources. I am confused on if closing
also closes the
object that will be created when I call
. Do I need to wrap
in a try-with-resources too?


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 Source

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.