java response close_java - 关闭连接后,如何使HttpResponse的HttpEntity字段持久化? - 堆栈内存溢出...

我在一个项目中,对一些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转储为String,然后在List或定制对象中返回状态代码和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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值