如何在关闭连接后使 HttpResponse 的 HttpEntity 字段保持不变?

How can I make the HttpEntity field of an HttpResponse persist after closing the connection?

我在一个项目中为一些 REST API 编写了很多测试。我有一个专用方法(和其他类似方法),HttpResponse sendRequest(String body, String url) 来执行请求,为我节省了一些样板代码。但是,我的问题是 HttpResponseHttpEntity 字段在关闭连接后不会持续存在。

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 转储到字符串 之前 我关闭连接,然后 return 状态代码和 HttpEntityList<String> 或自定义对象中,但这似乎很麻烦。如果我能以某种方式在本地保存 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;
}

关闭响应而不是请求。

这就是示例、教程和文档总是告诉我们要做的事情。

当然,您必须将其键入为 CloseableHttpResponse 而不仅仅是 HttpResponse。

使用 ByteArrayEntity。在关闭连接之前从默认 HttpEntity 收集流,使用流的内容创建一个新的 ByteArrayEntity,然后使用 response.setEntity(yourByteArrayEntity)。这将使实体持续存在。