簡體   English   中英

關閉連接后,如何使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轉儲為String,然后在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;
}

關閉響應而不是請求。

這就是示例,教程和文檔總是告訴我們的。

當然,您必須將其鍵入為CloseableHttpResponse而不是HttpResponse。

使用ByteArrayEntity 在關閉連接之前,從默認的HttpEntity收集流,使用流的內容創建一個新的ByteArrayEntity ,並使用response.setEntity(yourByteArrayEntity) 這將使實體持久化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM