Magnus
Magnus

Reputation: 728

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

I'm in a project where I write a lot of tests to some REST API. I have a dedicated method (and other similar methods), HttpResponse sendRequest(String body, String url) to do the requests, saving me some boilerplate clode. However, my problem is that the HttpEntity field of the HttpResponse does not persist after closing the connection.

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;
}

I could dump the HttpEntity to String before I close the connection, and then return both the status code and the HttpEntity in a List<String> or custom made object, but that seems like a lot of hassle. If I could just somehow save the HttpEntity locally, that would be better. What is the simplest way to solve my problem?


EDIT: What my sendRequest method looks like after I applied the solution in the accepted answer.

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;
}

Upvotes: 0

Views: 2392

Answers (2)

Use a ByteArrayEntity. Collect the stream from your default HttpEntity before you close the connection, make a new ByteArrayEntity with the contents of the stream, and use response.setEntity(yourByteArrayEntity). That will make the entity persist.

Upvotes: 1

kumesana
kumesana

Reputation: 2490

Close the response instead of the request.

That's what the examples, the tutorials and the documentations always tell to do.

Of course, you must type it as CloseableHttpResponse instead of just HttpResponse.

Upvotes: 1

Related Questions