Bri Veillette Bri Veillette - 2 years ago 494
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download