Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content and status code from HttpResponse [duplicate]

I am using apache's HttpClient (via the Fluent API). When I get the response object back, I first do:

response.returnResponse().getStatusLine().getStatusCode()

If status code is 4xx or 5xx, I throw an exception, or I return the content:

response.returnContent().asBytes();

The response here is an object of type Response. But when I run this, I am getting:

java.lang.IllegalStateException: Response content has been already consumed.

How can I get around this?

like image 803
Sayak Banerjee Avatar asked Dec 31 '13 23:12

Sayak Banerjee


People also ask

What is the HTTP status code for duplicate record?

409 Conflict - Client attempting to create a duplicate record, which is not allowed. 410 Gone - The requested resource has been deleted.

How do I get my HTTP status code 201 back?

To use the 201 HTTP Status Code in a website, the web developer should use the newly created resource. The newly created resource can be referred to by the URI(s) returned in the response entity, with the most specific URI for the resource provided by a Location header field.

What HTTP status code for user already exists?

A 403 - Already Exists error indicates that it is not possible to create a resource with the given definition because another resource already exists with the same attributes. Such errors always correspond with a 403 HTTP status code.


1 Answers

Both Response#returnResponse() and Response#returnContent() force the HttpResponse InputStream to be read. Since you can't read the InputStream twice, the library has put flag and a check to assert that the InputStream hasn't been consumed.

You don't get around this. What you do is get the underlying HttpResponse object and get both the status code and the body as bytes.

HttpResponse httpResponse = response.returnResponse();
httpResponse.getStatusLine().getStatusCode();
byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity());
like image 153
Sotirios Delimanolis Avatar answered Sep 28 '22 02:09

Sotirios Delimanolis