今天在使用httpclient 调用第三方接口的时候出现了socket closed错误。
经过一番百度,找到了原因。
原因是因为在封装HttpClientUtils时在finally块中将response关闭了。调用了response.closed方法
而在调用完后又需要将response转换成string,
public static CloseableHttpResponse doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
// String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
// resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return response;
CloseableHttpResponse carResult = HttpClientUtil.doPostJson(postUrl, carjson);
String resultString = EntityUtils.toString(carResult.getEntity(), "utf-8");
在转换成string时由于response流已经被关闭,从而导致无法被转换,导致报错。
解决方案:将finally块里的response.close()除去,在转换完之后关闭;或者重写httpclientutil ,返回类型根据自己所需。