Get content and status code from HttpResponse

I am using apache HttpClient (via Fluent API). When I return the response object, I first do:

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

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

 response.returnContent().asBytes(); 

response Here is an object of type response . But when I run this, I get:

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

How can I get around this?

+7
source share
1 answer

Both Response#returnResponse() and Response#returnContent() force the HttpResponse InputStream to be read. Since you cannot read InputStream twice, the library set a flag and checks that InputStream not used.

You will not do. 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()); 
+7
source

All Articles