HttpURLConnection wire logging in Android

2019-06-15 11:06发布

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?

Thanks

2条回答
可以哭但决不认输i
2楼-- · 2019-06-15 11:12

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();
查看更多
3楼-- · 2019-06-15 11:25

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());
    }
}
查看更多
登录 后发表回答