java - 将 CloseableHttpClient 与 try-with-resources 结合使用

标签 java apache-httpclient-4.x try-with-resources

<分区>

我一直在使用 try-with-resources 搜索 CloseableHttpClient 的完整示例。我很困惑,如果关闭 CloseableHttpClient 也会关闭将在我调用 httpclient.execute(post) 时创建的 CloseableHttpResponse 对象。我是否也需要将 CloseableHttpResponse 包装在 try-with-resources 中?

例子:

try(CloseableHttpClient httpclient = HttpClients.custom().build()) {
    HttpPost post = new HttpPost(url);
    CloseableHttpResponse res = httpclient.execute(post);

    // do something with res
} catch (Throwable e) {
    // do something with error
}

最佳答案

如果你想让响应参与你做的try-with-resource。虽然当您已经捕捉到异常时,您可以以 } 结束 - 不需要额外的捕捉。

从技术上讲,这不是 CloseableHttpResponse is emptyclose () 实现的要求

根据 httpcomponents 文档 (https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html),您需要关闭 CloseableHttpResponse 以释放资源

哦。 不要捕获 Throwable - 这是糟糕的风格,会导致很难发现错误。

关于java - 将 CloseableHttpClient 与 try-with-resources 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436621/

相关文章:

java - Akka Actors 失败,VerifyError : Inconsistent stackmap frames at branch target

java - try-with-resources 总是会关闭资源

java数组的arraylists

java - 似乎无法让 ESAPI Validator getValidInput() 处理 URL 参数

java : Understanding Arrays. asList(T...array) 原始类型方法

java - Apache PoolingHttpClientConnectionManager 抛出非法状态异常

java - 多线程应用程序中的 Apache HttpClient 和 HttpConnection

java - 未找到 API 包 'remote_socket' 或调用 'Resolve()' - GAE Java

java - 方法链接时 try-with-resources 中的 "Resource never closed"

Java ResultSet 跳过记录