0

I am debugging a Java application which makes use of the org.apache.http.* API such :

HttpResponse response = m_httpClient.execute(head,new BasicHttpContext());

That is just one example, my project is plenty of lines like that one, I would like insert a print log which should print the content and the headers, such:

Log.i(TAG, "---> Request <-----");
        String str = "";
        for (Header header : post.getAllHeaders())
        {
           str += header.getName() + " : " + header.getValue() + "\n";

        }
        Log.i(TAG, str);
        Log.i(TAG, "---> Response <-----");
        HttpResponse response = client.execute(post);
        Log.i(TAG, EntityUtils.toString(response.getEntity()));

        response = client.execute(post);

As workaround to avoid the "IllegalStateException: Content has been consumed" I am performing the request twice but I really do not like that, are there solutions to avoid this ?

pedr0
  • 2,941
  • 6
  • 32
  • 46
  • EntityUtils.toString indirectely consume HTTP response InputStream to build String object. The shortest solution would be to reuse that String latter. – Karol Król Oct 03 '14 at 17:59

2 Answers2

1

Which http client do you use?

Each httpclient flavor should have a googleable technique for "turn on Wire and Header logs"....

For example , if you were using the org.apache client, here is what you do to turn on the logs you are asking for..

With wire & header logs turned on, logcat includes what you see here

Community
  • 1
  • 1
Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43
0

After so quick research, this looks like it is a pretty prevalent exception.

Is there anyway you could just ask for the response string once? Store it in a method variable, log the response string and then return only the response string (instead of the entire HttpResponse object)?

Or is code further up the call chain actually working on other methods of the HttpResponse then just the content of the response?

One other idea I've had, but isn't super fun to write, is you could implement all the different HttpResponse interfaces yourself, and write behavior that will 'cache' all the possible behavior of the original HttpResponse object. Basically, wrapper the original HttpResponse with your own object. Seems like a lot of work, but it would work for what you're doing, hopefully.

hooknc
  • 4,854
  • 5
  • 31
  • 60