使用资源在嵌套尝试中移动 CloseableHttpResponse

Move CloseableHttpResponse inside nested try with resources

我有以下代码,使用 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);
        }
    }
}

我可以安全地替换为资源的嵌套尝试吗:

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);
}

还是对资源块使用一次尝试更好:

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

有时重构为单个块是有问题的,所以我想知道 nested/additional 块是一个有效的解决方案。

HttpClient 从不 returns 空 HttpResponse 对象。第一个构造根本没有用。第二个和第三个构造都完全有效