Move CloseableHttpResponse inside nested try with resources

2.4k views Asked by At

I have the following code using try with resources with CloseableHttpResponse

CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.custom().build()){    
    //code...
    response = httpClient.execute(target, post);
    String responseText = EntityUtils.toString(response.getEntity());   
} catch (Exception e) {
    logger.error("Failed sending request", e);
} finally {
    if (response != null) {
        try {
            response.close();
        } catch (IOException e) {
            logger.error("Failed releasing response", e);
        }
    }
}

Can I safely replace with nested try with resources:

try (CloseableHttpClient httpClient = HttpClients.custom().build()){
    URIBuilder uriBuilder = new URIBuilder(url);
    HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
    HttpPost post = new HttpPost(uriBuilder.build());
    try (CloseableHttpResponse response = httpClient.execute(target, post)) {
        String responseText = EntityUtils.toString(response.getEntity());   
    }
} catch (Exception e) {
    logger.error("Failed sending request", e);
}

Or is it better to use a single try with resources block:

try (CloseableHttpClient httpClient = HttpClients.custom().build();
    CloseableHttpResponse response = getResponse(httpClient, url)) {

Sometime refactoring to single block is problematic, so I wanted to know the a nested/additional block is a valid solution.

1

There are 1 answers

8
ok2c On BEST ANSWER

HttpClient never returns a null HttpResponse object. The first construct is simply not useful. Both the second and the third constructs are perfectly valid