Using CloseableHttpClient with try-with-resources

I was looking for a complete example CloseableHttpClientusing try-with-resources. I am confused if closing CloseableHttpClientalso closes the object CloseableHttpResponsethat will be created when called httpclient.execute(post). Do I need to wrap CloseableHttpResponsein 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
}
+4
source share
1 answer

If you want the answer to participate in a try-with-resource, you do. Although after you catch the Exceptions already, you can end up with} - no extra trick is required.

, close () CloseableHttpResponse

. Throwable - .

+6

Source: https://habr.com/ru/post/1621459/


All Articles