【发布时间】:2018-07-16 11:56:02
【问题描述】:
我在一个项目中,我为一些 REST API 编写了很多测试。我有一个专用方法(和其他类似方法)HttpResponse sendRequest(String body, String url) 来执行请求,为我节省了一些样板代码。但是,我的问题是HttpResponse 的HttpEntity 字段在关闭连接后不会持续存在。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClient;
...
protected HttpClient client;
...
protected void testMyHttpAPI(){
String body = makeBody();
String url = "http://localhost/myAPI";
HttpResponse response = sendRequest(body, url); //This successfully returns an HttpResponse
assertEquals(response.getStatusLine().getStatusCode(),200); //This checks out
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity); //This line crashes
}
protected HttpResponse sendRequest(String body, String url){
HttpEntity entity = makeEntity(body);
HttpGet get = new HttpGet(url);
get.setEntity(entity);
HttpResponse response = client.execute(get);
get.releaseConnection(); //Here I *close* the connection before I return the HttpResponse.
return response;
}
我可以在关闭连接之前将HttpEntity 转储为字符串,然后在List<String> 或自定义对象中返回状态代码和HttpEntity,但这似乎很麻烦。如果我能以某种方式将HttpEntity 保存在本地,那就更好了。解决我的问题的最简单方法是什么?
编辑:我在接受的答案中应用解决方案后,我的sendRequest 方法的样子。
import org.apache.http.HttpEntity;
import org.apache.http.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.CloseableHttpClient;
...
protected CloseableHttpClient client;
...
protected CloseableHttpResponse sendRequest(String body, String url){
HttpEntity entity = makeEntity(body);
HttpGet get = new HttpGet(url);
get.setEntity(entity);
CloseableHttpResponse response = client.execute(get);
response.close();
get.releaseConnection();
return response;
}
【问题讨论】:
标签: java apache-httpcomponents