如何解决为什么尝试使用资源会导致 CloseableHttpClient 出现截断块错误?
你能帮我解决以下问题吗: 我有以下方法:
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: Truncated chunk (expected size: 379; actual size: 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);
}
我完全没有错误!你能解释一下 - 有什么问题吗?我是新手,不知道 - 互联网上的一些例子运行良好......
解决方法
try-with-resources 块将自动调用对象上的 close()
,因此从这些 getRequest
调用之一返回的是一个关闭的 CloseableHttpClient 实例。
没有 try-with-resources 的调用将返回一个工作(未关闭)的 CloseableHttpClient。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。