我有以下代码使用try with resources withCloseableHttpResponse
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)) {
有时重构为单个块是有问题的,所以我想知道嵌套/附加块是一个有效的解决方案。