使用Apache HttpClient的execute方法是否需要手动关闭? [重复]

问题描述 投票:0回答:1

我目前正在使用 Apache HttpClient 在我的 Java 应用程序中执行 HTTP 请求。我遇到过不同的示例和片段,其中关闭响应的处理有所不同,这让我对这个库的资源管理最佳实践有点困惑。

根据我的理解,当使用 HttpClient 的

execute
方法时,响应资源似乎在某些上下文中自动管理,特别是在使用响应处理程序时。例如,当使用
HttpClientResponseHandler
execute
方法时,看起来库会负责为您关闭响应:

HttpResponse response = httpClient.execute(httpGet, responseHandler);

但是,我见过其他代码示例,其中开发人员手动关闭响应,即使使用类似的模式也是如此:

CloseableHttpResponse response = httpClient.execute(httpGet);
try {
    // Process the response
} finally {
    response.close();
}

这是org.apache.hc.client5.http.impl.classic.CloseableHttpClient中的execute方法。响应位于 try-with 块中

public <T> T execute(
            final HttpHost target,
            final ClassicHttpRequest request,
            final HttpContext context,
            final HttpClientResponseHandler<? extends T> responseHandler) throws IOException {
        Args.notNull(responseHandler, "Response handler");

        try (final ClassicHttpResponse response = doExecute(target, request, context)) {
            try {
                final T result = responseHandler.handleResponse(response);
                final HttpEntity entity = response.getEntity();
                EntityUtils.consume(entity);
                return result;
            } catch (final HttpException t) {
                // Try to salvage the underlying connection in case of a protocol exception
                final HttpEntity entity = response.getEntity();
                try {
                    EntityUtils.consume(entity);
                } catch (final Exception t2) {
                    // Log this exception. The original exception is more
                    // important and will be thrown to the caller.
                    LOG.warn("Error consuming content after an exception.", t2);
                }
                throw new ClientProtocolException(t);
            }
        }
    }

鉴于上述情况,我的问题是:

  1. 当将 Apache HttpClient 的执行方法与响应处理程序一起使用时,是否需要手动关闭响应,或者库会为您处理它?
  2. 如果库确实处理关闭,这是否适用于所有类型的响应,包括来自 CloseableHttpClient 和带有响应处理程序的 HttpClient 的响应?

我正在寻找有关最佳实践的指导,以确保正确的资源管理,同时避免应用程序中的内存泄漏或资源耗尽。

预先感谢您的见解和帮助!

编辑:不,我的问题与建议的答案不相似,因为我使用的是 httpclient5-5.2.1 而不是 httpclient 4.5.x

Edit2:你想知道为什么人们更喜欢使用 ChatGpt。

java apache-commons-httpclient
1个回答
0
投票

是的。

您可以使用 try-with-resources 使您的代码更加清晰。

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    // Process the response
}

您可以查看这篇文章以获取更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.