Reputation: 73753
How can I log a response from HttpResponse
and then process the response after.
for example when I do this
HttpEntity entity = resp.getEntity();
String xml = EntityUtils.toString(entity);
InputStream is = entity.getContent();
i get the exception java.lang.IllegalStateException: Content has been consumed
because I wrote the entity to a string. I only want to use that string for debugging and then use the InputStream to process all the content in the response
Upvotes: 0
Views: 105
Reputation: 50538
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
String asString = getString(is);
Log.i(TAG,""+asString);
The point is to avoid closing the InputStream
with is.close()
or flushing it with is.flush()
, to have it later for processing. The exception is thrown because the content is converted as InputStream
by calling EntityUtils.toString(entity);
public static String getString( InputStream is) throws IOException {
int ch;
StringBuilder sb = new StringBuilder();
while((ch = is.read())!= -1)
sb.append((char)ch);
return sb.toString();
}
Don't forget to close the stream after you are done with the processing.
Upvotes: 1
Reputation: 4471
Here is an example of a code block that can be used to convert an HttpResponse
into a String
:
String output = inputStreamToString(httpResponse.getEntity().getContent()).toString();
public static StringBuilder inputStreamToString(InputStream is){
String line;
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
Upvotes: 0