This question already has answers here:
What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

(7 个回答)


去年关闭。




我一直在寻找带有 try-with-resources 的 CloseableHttpClient 的完整示例。我很困惑关闭 CloseableHttpClient 是否也会关闭我调用 CloseableHttpResponse 时将创建的 httpclient.execute(post) 对象。我是否也需要将 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
}

最佳答案

如果您希望响应参与资源尝试,您可以这样做。尽管您已经捕获了异常,但可以以 } 结尾 - 不需要额外的捕获。

从技术上讲 它不是 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/

10-09 19:50