【问题标题】:How can I make the HttpEntity field of an HttpResponse persist after closing the connection?关闭连接后,如何使 HttpResponse 的 HttpEntity 字段持续存在?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      关闭响应而不是请求。

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

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

      【讨论】:

      • 谢谢!这确实有效,但直到我关闭响应除了请求,而不是代替它。
      • @Magnus ??我不知道什么样的代码看起来像你描述的那样,同时产生你想要的结果。
      • 没关系,你帮了大忙。我已经用我的最终代码的样子更新了 OP。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多