Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to close CloseableHttpResponse/CloseableHttpClient [duplicate]

I'm using CloseableHttpResponse (from apache-httpclient-4.5.3) and I'm not sure I'm using it right, I saw an answer with no votes to use EntityUtils.consume on finally:

CloseableHttpResponse response1 = httpclient.execute(httpGet);

try {

 System.out.println(response1.getStatusLine());

} finally {

 EntityUtils.consume(response1.getEntity());

CloseableHttpClient is abstract and has no close method to call although in this answer it's used:

CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //do something
} finally {
    response.close();
}

Currently I'm using try with resources for CloseableHttpClient and CloseableHttpResponse inside of send method.

Am I not missing any resource open or using it in a wrong way?

private CloseableHttpResponse send()
            throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
        URIBuilder uriBuilder = new URIBuilder(BASE_URL);
        HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
        HttpPost post = new HttpPost(uriBuilder.build());
        try (CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(target, post)) {            
            return response;
        }
    
like image 459
user7294900 Avatar asked Feb 22 '18 13:02

user7294900


2 Answers

It has been explained in detail in the docs here.
Quoting the pseudo code from the docs here's a typical way to allocate/deallocate an instance of CloseableHttpClient:

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
    <...>
}

The same applies to CloseableHttpResponse :

try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    <...>
}

Now, about the close method in CloseableHttpClient. CloseableHttpClient is an abstract class that implements Closeable interface. That is, although it doesn't have a close method itself the classes that extend it are required to implement the close method. One class is InternalHttpClient. You can check the source code for the details.

Before Java7, explicit close would be required:

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    <...>
} finally {
    httpclient.close();
}

CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}
like image 101
atoMerz Avatar answered Oct 22 '22 20:10

atoMerz


You can avoid the finally by using the try(resource)

try (CloseableHttpResponse response = httpclient.execute(httpGet)) { ... }

like image 27
dvallejo Avatar answered Oct 22 '22 22:10

dvallejo