简体   繁体   English

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

[英]Move CloseableHttpResponse inside nested try with resources

I have the following code using try with resources with CloseableHttpResponse 我有以下代码,对带有CloseableHttpResponse资源使用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替换资源:

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

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. 有时重构为单个块是有问题的,所以我想知道嵌套/附加块是有效的解决方案。

HttpClient never returns a null HttpResponse object. HttpClient永远不会返回空的HttpResponse对象。 The first construct is simply not useful. 第一种构造根本没有用。 Both the second and the third constructs are perfectly valid 第二和第三种构造都是完全有效的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM