Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple logging interceptor for OkHttp that logs full request headers and response headers + body (useful for use with Retrofit 2 where logging was removed)
if (BuildConfig.DEBUG) {
httpclient.interceptors().add(new LoggingInterceptor());
}
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Buffer requestBuffer = new Buffer();
request.body().writeTo(requestBuffer);
Log.d("OkHttp", requestBuffer.readUtf8());
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType contentType = response.body().contentType();
BufferedSource buffer = Okio.buffer(new GzipSource(response.body().source()));
String content = buffer.readUtf8();
Log.d("OkHttp", content);
ResponseBody wrappedBody = ResponseBody.create(contentType, content);
return response.newBuilder().removeHeader("Content-Encoding").body(wrappedBody).build();
}
}
if (BuildConfig.DEBUG) {
httpclient.interceptors().add(new LoggingInterceptor());
}
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Buffer requestBuffer = new Buffer();
request.body().writeTo(requestBuffer);
Log.d("OkHttp", requestBuffer.readUtf8());
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType contentType = response.body().contentType();
String content = response.body().string();
Log.d("OkHttp", content);
ResponseBody wrappedBody = ResponseBody.create(contentType, content);
return response.newBuilder().body(wrappedBody).build();
}
}
@bradroid
Copy link

bradroid commented Dec 7, 2015

Hi, one question: why do you create new response at the end of the block with

ResponseBody wrappedBody = ResponseBody.create(contentType, content);
        return response.newBuilder().body(wrappedBody).build();

can't you just return the response object you got in line 17?

return response;

@Nxele
Copy link

Nxele commented Jan 31, 2019

Hi erickok

i need help I'm new to interceptors how can i execute this interceptor so it addHeader

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    if (BuildConfig.DEBUG) {
        httpClient.interceptors().add(new Interceptor() {

            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                Toast.makeText(getApplicationContext(),"Please work now", Toast.LENGTH_LONG).show();
                Request request = original.newBuilder()
                        //.header("User-Agent", "AirbusMapBox")
                        .addHeader("Authorization",Airbus_key)
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = httpClient.build();

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://view.geoapi-airbusds.com")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    }

@behelit
Copy link

behelit commented Dec 9, 2019

This doesn't seem to log timeout's or exceptions

@colymore
Copy link

colymore commented Nov 18, 2020

Hi, one question: why do you create new response at the end of the block with

ResponseBody wrappedBody = ResponseBody.create(contentType, content);
        return response.newBuilder().body(wrappedBody).build();

can't you just return the response object you got in line 17?

return response;

I think it's because the stream is closed when prints body

@flocsy
Copy link

flocsy commented Jul 12, 2021

Here's a merged version that can log gzip and non-gzip responses as well:

public class ResponseLoggingInterceptor implements Interceptor {
    
        public static final String CONTENT_ENCODING = "content-encoding";
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
    
            String content = null;
            ResponseBody body = response.body();
            if (body != null) {
                MediaType contentType = body.contentType();
                String contentEncoding = response.header(CONTENT_ENCODING);
                if ("gzip".equals(contentEncoding)) {
                    BufferedSource buffer = Okio.buffer(new GzipSource(body.source()));
                    content = buffer.readUtf8();
                    ResponseBody wrappedBody = ResponseBody.create(contentType, content);
                    response = response.newBuilder().removeHeader(CONTENT_ENCODING).body(wrappedBody).build();
                } else {
                    content = body.string();
                    ResponseBody wrappedBody = ResponseBody.create(contentType, content);
                    response = response.newBuilder().body(wrappedBody).build();
                }
            }
            String protocol = response.protocol().name().replaceFirst("_", "/");
            protocol = protocol.replace('_', '.');
            String httpLine = "" + protocol + ' ' + response.code();
            Log.v("OkHttp", String.format("%s\n%s\n\n%s", httpLine, response.headers(), content));
    
            return response;
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment