【问题标题】:Why try-with-resources causes Truncated chunk error with CloseableHttpClient?为什么 try-with-resources 会导致 CloseableHttpClient 出现截断块错误?
【发布时间】:2021-05-12 10:36:24
【问题描述】:

请您帮我解决以下问题: 我有以下方法:

public static CloseableHttpResponse getRequest (String url) {
    try (CloseableHttpClient httpClient = HttpClients.createDefault();){
        HttpGet httpget = new HttpGet(url); //http get request (create get connection with particular url)
        return httpClient.execute(httpget);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

我在哪里使用 CloseableHttpClient 和 try-with-resources 我在一些简单的测试中调用方法:

CloseableHttpResponse closeableHttpResponse = RestClient.getRequest("https://reqres.in/api/users?page=2");
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
JSONObject responseJson = new JSONObject(responseString);
System.out.println(responseJson);

我收到错误:org.apache.http.TruncatedChunkException:截断块(预期大小:379;实际大小:358)

当我不使用 try-with-resources 时:

public static CloseableHttpResponse getRequest (String url) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url); //http get request (create get connection with particular url)
    return httpClient.execute(httpget);
}

我完全没有错误!你能解释一下 - 怎么了?我是新手,不知道 - 互联网上的一些例子效果很好......

【问题讨论】:

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


【解决方案1】:

try-with-resources 块将自动调用对象上的close(),因此其中一个getRequest 调用的返回是一个关闭的 CloseableHttpClient 实例。

没有 try-with-resources 的调用将返回一个工作(未关闭)的 CloseableHttpClient。

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 2017-08-03
    • 2013-05-09
    • 2018-10-20
    • 2014-10-19
    • 1970-01-01
    • 2012-02-21
    • 2020-12-02
    • 2014-01-06
    相关资源
    最近更新 更多