6

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
}
Bri Veillette
  • 323
  • 1
  • 3
  • 11

1 Answers1

7

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.

tkruse
  • 10,222
  • 7
  • 53
  • 80
Jan
  • 13,738
  • 3
  • 30
  • 55
  • 1
    Thanks, for the Throwable tip. It was like that in the code base, and I didn't know any better! I will change that. – Bri Veillette Dec 23 '15 at 13:25
  • @Jan Do you have any reference for this requirement? – Chriki Dec 23 '15 at 13:26
  • 1
    I wish I could give more upvotes for 'Don't catch Throwable'. – ok2c Dec 23 '15 at 13:42
  • @oleg and Jan is there any good reason to use `Throwable` at all or just flat out never use it? – Bri Veillette Dec 23 '15 at 13:53
  • Your link to the "empty" close method in CloseableHttpResponse is broken, but CloseableHttpResponse is an *interface*, so it won't have implementation of the close() method. It *is* a requirement that you run the close method because any CloseableHttpResponse implementation *should* have implemented the close() method properly. – zeusalmighty Jul 18 '18 at 16:43