【发布时间】: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);
}
我完全没有错误!你能解释一下 - 怎么了?我是新手,不知道 - 互联网上的一些例子效果很好......
【问题讨论】:
-
欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后edit你的问题包括你拥有的完整源代码作为minimal reproducible example,其他人可以编译和测试。请参阅:Why is “Can someone help me?” not an actual question?.
-
随后的编辑确实开始使这个问题越来越恶化......我已经回滚到事情变得更有意义的时候。说真的,到底发生了什么?大声笑
标签: java apache-httpclient-4.x try-with-resources truncated