Is it possible to get both the status code and the body content when using Apache HttpClient's Facade? [duplicate]

StackOverflow https://stackoverflow.com/questions/22409303

Question

I am using Apache's HttpClient Fluent Facade in Java in some sample code for developers to extend. They really like the fluent facade, with its capability to just call:

this.body = Request.Get(uri.build()).execute().returnContent().asString();

Additionally, I could get the status code by callling:

this.statusCode = Request.Get(uri.build()).execute().returnResponse().getStatusLine().getStatusCode();

Unfortunately, there are several instances where I need the status code in addition to the body. Based on this question, I see that I could have them learn the HttpClient object -

HttpResponse response = client.execute(httpGet);
String body = handler.handleResponse(response);
int code = response.getStatusLine().getStatusCode();

but, that means initializing the HttpClient object and seemingly rejecting the Fluent interface and the Request.Get (or Post) syntax. Is there a way to get both the status code and the body without losing the Fluent syntax and without making two discrete calls?

Was it helpful?

Solution

Yes, it is, though you'll have to handle the Response object yourself. Here's an example of how I've done it in the past:

org.apache.http.HttpResponse response = Request.Get(url)
    .connectTimeout(CONNECTION_TIMEOUT_MILLIS)
    .socketTimeout(SOCKET_TIMEOUT_MILLIS)
    .execute()
    .returnResponse();

int status = response.getStatusLine().getStatusCode();
byte[] serializedObject = EntityUtils.toByteArray(response.getEntity());

There are several methods to retrieve the body content using EntityUtils. In this case I was retrieving a serialized object from a cache, but you get the idea. I really don't believe this is a departure from the Fluent API, but I guess that's a matter of opinion. The problem is that using the Fluent returnXXX methods, the response is fully consumed and closed so you have to get the things you need from the response itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top