Can I get the status code and body content when using the Apache HttpClient Facade?

I am using the Apache HttpClient Fluent Facade in Java in some sample code for developers. They really like the smooth facade with the ability to just make calls:

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

In addition, I could get the status code by calling:

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

Unfortunately, there are several cases when I need a status code in addition to the body. Based on this question , I see that I could examine their HttpClient object -

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

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

+6
source share
1 answer

Yes, it is, although you will have to process the Response object yourself. Here is an example of how I did this in the past:

 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 ways to get body content using EntityUtils. In this case, I retrieved the serialized object from the cache, but you understood this idea. I really don't think this is a departure from the Fluent API, but I think it is a matter of opinion. The problem is that, using the Fluent returnXXX methods, the answer is completely absorbed and closed, so you need to get the things you need from the answer itself.

+11
source

All Articles