我正在使用CloseableHttpResponse(来自apache-httpclient-4.5.3),但我不确定我是否使用正确,我看到一个没有投票的答案,建议在finally中使用EntityUtils.consume
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
} finally {
EntityUtils.consume(response1.getEntity());
CloseableHttpClient
是一个抽象类,虽然在这个 answer 中被使用,但它本身没有 close 方法可供调用:
CloseableHttpResponse response = httpclient.execute(httpget);
try {
//do something
} finally {
response.close();
}
目前我在send方法中使用try with resources处理CloseableHttpClient和CloseableHttpResponse。
我是否遗漏了任何资源的打开或错误使用任何资源?
private CloseableHttpResponse send()
throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
URIBuilder uriBuilder = new URIBuilder(BASE_URL);
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
HttpPost post = new HttpPost(uriBuilder.build());
try (CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(target, post)) {
return response;
}