java - 关闭 CloseableHttpResponse/CloseableHttpClient 的正确方法

标签 java apache-httpclient-4.x resource-cleanup autocloseable

<分区>

我正在使用 CloseableHttpResponse(来自 apache-httpclient-4.5.3)但我不确定我是否正确使用它,我看到了一个 answer with no votes最后使用 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();
}

目前,我在发送方法中尝试使用 CloseableHttpClientCloseableHttpResponse 的资源。

我是否遗漏了任何打开的资源或以错误的方式使用它?

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;
        }
    

最佳答案

在文档中有详细解释here .
引用文档中的伪代码是分配/解除分配 CloseableHttpClient 实例的典型方法:

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
    <...>
}

这同样适用于 CloseableHttpResponse:

try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    <...>
}

现在,关于 CloseableHttpClient 中的关闭方法。 CloseableHttpClient 是一个实现Closeable 接口(interface)的抽象类。也就是说,虽然它本身没有 close 方法,但是扩展它的类需要实现 close 方法。一类是 InternalHttpClient。您可以查看源代码以获取详细信息。

在 Java7 之前,需要显式关闭:

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    <...>
} finally {
    httpclient.close();
}

CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}

关于java - 关闭 CloseableHttpResponse/CloseableHttpClient 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48928930/

相关文章:

java - Junit 测试中没有错误类型的合格 bean

java - 使用 HttpAsyncClients 设置重试次数

python-3.x - 使用 Flask 开发服务器重新加载器处理多个应用程序对象的 atexit

使用 dlsym 清理函数插入

java - 如何从 UML 转换为 java。虚线关系

java - RMI 导出对象(远程对象,端口);创建注册表(端口);

java - 在 Java 中使用 Apache HTTP 处理丢失的资源

regex - 无法否定nexus sonatype正则表达式模式

java - IText 7 : How to build a mix of text and attachments to the paragraph?

java - 如何在 Apache HttpClient 中使用 SSL 客户端证书?