在资源的嵌套尝试中移动CloseableHttpResponse

时间:2018-12-28 15:38:17

标签: java httpresponse apache-httpclient-4.x try-with-resources closeablehttpresponse

我有以下代码,对带有CloseableHttpResponse的资源使用try

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替换资源吗?

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更好?

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

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

1 个答案:

答案 0 :(得分:1)

HttpClient永远不会返回空的HttpResponse对象。第一种构造根本没有用。第二和第三种构造都是完全有效的