问题描述
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。