20

I'm trying to get all the headers for request/response in my logcat. Seems there is no easy way with HttpURLConnection as it is with org.apache.http.

According to this blog you can do:

sun.net.www.protocol.http.HttpURLConnection.level = ALL

Seems this was removed from Android implementation for HttpURLConnection. Is there any easy way to sniff requests/responses on logcat?

j.developer
  • 474
  • 2
  • 5
  • 15
Daniel Bogdan
  • 758
  • 10
  • 23

3 Answers3

1

This is something you can easily do yourself:

private static void logConnection(HttpURLConnection httpConnection) throws IOException {
    int status = httpConnection.getResponseCode();
    Log.d("logConnection", "status: " + status);
    for (Map.Entry<String, List<String>> header : httpConnection.getHeaderFields().entrySet()) {
        Log.d("logConnection", header.getKey() + "=" + header.getValue());
    }
}
Rhand
  • 901
  • 7
  • 20
  • With Your code you'll log only the Response Code and Header. The request will be consumed and is not accessible anymore – Rafael T Oct 04 '14 at 14:24
  • 2
    This is just the logging, you'd call this from the method where you process the request. e.g open connection, log response code (by calling logConnection()), process response. – Rhand Oct 15 '14 at 12:48
0

Perhaps this link would help: https://stackoverflow.com/a/37525989/11845778 Though, you would still need to do the logcat part. This just gets the response as JSON.

OldMember
  • 59
  • 1
  • 7
-3

I am not sure it is possible with standard HttpURLConnection on Android. Therefore it is easy to achieve using OkHttp library:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.addInterceptor(loggingInterceptor);

OkHttpClient client = httpClientBuilder.build();
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url("http://android.com");

client.newCall(requestBuilder.build()).execute();
Alex Radzishevsky
  • 3,416
  • 2
  • 14
  • 25