首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否需要显式关闭CloseableHttpClient和CloseableHttpResponse?

是否需要显式关闭CloseableHttpClient和CloseableHttpResponse?
EN

Stack Overflow用户
提问于 2019-09-23 21:23:18
回答 1查看 780关注 0票数 2

我有以下方法,它发出一个HTTP POST请求。

它返回一个CloseableHttpResponse,因此任何调用它的代码都可以获得状态代码、响应体等。

我试着去理解,这两个:

  • CloseableHttpClient client
  • CloseableHttpResponse closeableHttpResponse

需要关闭吗?还是关闭一个,关闭另一个?

代码语言:javascript
复制
..
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;

public static CloseableHttpResponse post(final String restEndpoint, final String data, final Header[] headers) throws Exception {
    final URIBuilder uriBuilder = new URIBuilder(restEndpoint);
    final HttpPost httpPost = new HttpPost(uriBuilder.build());
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Cache-Control", "no-cache, no-store");

    if (data != null) {
        httpPost.setEntity(new StringEntity(data));
    }

    if (headers != null) {
        for (Header header : headers) {
            httpPost.setHeader(header);
        }
    }

    final CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(createSSLFactory())
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();

    final CloseableHttpResponse closeableHttpResponse = client.execute(httpPost);
    final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
    logger.debug(Optional.empty(), statusCode, httpPost.toString());

    return closeableHttpResponse;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-23 22:14:06

我认为CloseableHttpResponse需要手动关闭每个单独的请求。

有几种方法可以做到这一点。

使用try/catch/finally块:

代码语言:javascript
复制
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class CloseableHttpClientWithTryCatchFinally {

    public static void main(String... args) throws Exception {

        URIBuilder uriBuilder = new URIBuilder("https://www.google.com/");

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        CloseableHttpClient client = HttpClients.custom().build();

        CloseableHttpResponse response = null;

        try {
            response = client.execute(httpGet);

            response.getEntity().writeTo(System.out);

        } catch (IOException e) {

            System.out.println("Exception: " + e);
            e.printStackTrace();

        } finally {

            if (response != null) {
                response.close();
            }
        }
    }
}

我认为更好的答案是使用尝试-with-resources语句

代码语言:javascript
复制
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class CloseableHttpClientTryWithResources {

    public static void main(String... args) throws Exception {

        URIBuilder uriBuilder = new URIBuilder("https://www.google.com/");

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        CloseableHttpClient client = HttpClients.custom().build();

        try (CloseableHttpResponse response = client.execute(httpGet)) {

            response.getEntity().writeTo(System.out);

        } catch (IOException e) {

            System.out.println("Exception: " + e);
            e.printStackTrace();
        }
    }
}

通常,我看到人们只为他们的应用程序创建一个CloseableHttpClient,然后在整个应用程序中重用该实例。如果你只会一次又一次地使用一个或几个实例,那么不,我认为你不应该关闭它们。但是,如果要一次又一次地创建CloseableHttpClient的新实例,则需要关闭它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58070374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档