【问题标题】:Right way to close CloseableHttpResponse/CloseableHttpClient [duplicate]关闭 CloseableHttpResponse/CloseableHttpClient 的正确方法 [重复]
【发布时间】:2018-08-02 09:25:51
【问题描述】:

我正在使用 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 中使用了它:

CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //do something
} finally {
    response.close();
}

目前我在发送方法中使用 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;
        }
    

【问题讨论】:

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


    【解决方案1】:

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

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

    同样适用于CloseableHttpResponse:

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

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

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

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

    【讨论】:

    • 我使用try with resources 的方法同样可以接受吗?
    • 是的。有几种方法可以释放Closeable 资源,其中一种是try-with-resources。但是,这取决于您的用例如何以及何时关闭资源。
    • 在这种情况下,我只是创建请求并执行它。使用try with resources 似乎是正确的方法
    • 不需要EntityUtils.consume(response.getEntity())?
    • @user7294900 如果您不确定您的代码是否总是消耗整个响应消息内容,可以这样做。 try-with-resources 是正确的方法,但它并不否定 atoMerz 概述的基本原则
    【解决方案2】:

    你可以通过使用 try(resource) 来避免 finally

    try (CloseableHttpResponse 响应 = httpclient.execute(httpGet)) { ... }

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多