String result = EntityUtils.toString(response.getEntity());获取不到返回值,返回“”

我当初使用HttpPost方法请求一个url,返回一个CloseableHttpResponse 对象。如下:
CloseableHttpResponse response = HttpClientUtil.doGetHeader(zfDownUrl,param,headers,proxy);
然后使用:String result = EntityUtils.toString(response.getEntity(), "UTF-8");竟然获取到的值是“”

当时很好奇明明这个url是有返回值的,返回的是json对象。为毛使用HttpClinet去请求就没有返回值呢。并且状态码都是200.

经过我的查找发现doGetHeader方法内部在执行完httpClient.execute(httpGet);以后就把response给关闭了才导致获取不到的!

如下导致获取不到值的代码:

CloseableHttpResponse response = httpClient.execute(httpGet);
if (response != null){
   response.close();
}
if (httpClient != null){
   httpClient.close();
}

return response;

改为:
CloseableHttpResponse response = httpClient.execute(httpGet);

return response;

就可以了。

还有一个原因是:entity所得到的流是不可重复读取的也就是说所得的到实体只能一次消耗完,不能多次读取,也就是说获取不到值也有可能是EntityUtils.toString(response.getEntity(), "UTF-8");这段代码已经被执行过一次了

你可能感兴趣的:(java)