我有一个httpClient函数,它将一个HttpResponse对象返回给调用函数。
public HttpResponse postRequest(String uri, String body) throws IOException {
HttpResponse response;
String url = baseUrl + uri;
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.build()) {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(body));
post.setHeader(AUTHORIZATION_HEADER, authorization);
post.setHeader(CONTENTTYPE_HEADER, APPLICATION_JSON);
post.setHeader(ACCEPT_HEADER, APPLICATION_JSON);
response = httpClient.execute(post);
} catch (IOException e) {
System.out.println("Caught an exception" + e.getMessage().toString());
logger.error("Caught an exception" + e.getMessage().toString());
throw e;
}
return response;
}
在我的调用函数中,我调用HttpResponse response = httpRequest.postRequest(url,body);
(其中httpRequest是包含函数的类的对象
当我尝试通过
解析收到回复的内容时String responseString = IOUtils.toString(response.getEntity()
.getContent(), "UTF-8");
我收到错误Socket已关闭。
关闭连接后,如何使用HttpResponse的内容?
答案 0 :(得分:0)
您的try-with-resources语句正在关闭整个客户端。你不希望这样。去掉它。当呼叫者关闭您要返回的响应时,您希望关闭发生。