使用带有try-with-resources的CloseableHttpClient

时间:2015-12-23 13:18:37

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

我一直在寻找带有try-with-resources的CloseableHttpClient完整示例。如果关闭CloseableHttpClient也会关闭我调用CloseableHttpResponse时将创建的httpclient.execute(post)对象,我感到很困惑。我是否还需要在资源试用中包装CloseableHttpResponse

示例:

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
}

1 个答案:

答案 0 :(得分:6)

如果您希望响应能够参与资源试用。虽然你已经抓住了例外,但你可以结束} - 不需要额外的捕获。

从技术上讲这不是一项要求,因为CloseableHttpResponse is emptyclose ()的实施

喔。 不要抓住Throwable - 这是糟糕的风格,可能导致很难找到错误。

相关问题