Java 将CloseableHttpResponse移动到嵌套的try with resources中

Java 将CloseableHttpResponse移动到嵌套的try with resources中,java,httpresponse,apache-httpclient-4.x,try-with-resources,closeablehttpresponse,Java,Httpresponse,Apache Httpclient 4.x,Try With Resources,Closeablehttpresponse,我使用try with resources withCloseableHttpResponse CloseableHttpResponse response = null; try (CloseableHttpClient httpClient = HttpClients.custom().build()){ //code... response = httpClient.execute(target, post); String responseText = E

我使用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);
        }
    }
}
我是否可以安全地替换为嵌套的try-with资源:

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)) {

有时重构到单个块是有问题的,所以我想知道嵌套/附加块是有效的解决方案。

HttpClient从不返回null
HttpResponse
对象。第一个构造根本没有用处。第二个和第三个构造都是完全有效的

使用嵌套/附加的try with resources块是否有问题?不,没有。但是,通常不应该为每个请求创建一个新的HttpClient实例。这是非常浪费和低效的。您指的是像在连接池中使用持久连接一样使用
PoollighttpClientConnectionManager
,这当然是一件不应该扔掉的事情,但其他昂贵的操作,如SSL/TLS上下文初始化,理想情况下只能在运行时执行一次。您对SSL的评论是否也与每小时1个请求相关?