Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 409
Affable Geek Avatar asked Mar 14 '14 15:03

Affable Geek


People also ask

How do you get a response body from Clienthttpresponse?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

What is closeable HttpClient?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated. The HttpClient is an interface for this class and other classes. You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder .


1 Answers

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.

like image 65
jgitter Avatar answered Sep 22 '22 18:09

jgitter