Intercept OkHttpClient Response for Debug
1 min read

Intercept OkHttpClient Response for Debug

Intercept OkHttpClient Response for Debug

I wanted to log the data retrieved by OkHttpClient for debugging purposes. After digging for a while, the process seems quite straight-forward now.

First, we create the OkHttpClient:

OkHttpClient client = new OkHttpClient();

Then, we add an interceptor:

client.interceptors().add((chain) -> { /** Interceptor code **/ }

The interceptor code is:

//Current Request
Request originalRequest = chain.request();

//Get response of the request
Response response = chain.proceed(originalRequest);

if (BuildConfig.DEBUG) {
    // I am logging the response body in debug mode.
    // When I do this I consume the response (OKHttp only lets you do this once)
    // so I have re-build a new one using the cached body
    String bodyString = response.body().string();
    Timber.d("Sending request %s with headers %s ",
        originalRequest.url(), originalRequest.headers());
    Timber.d("Got response HTTP %s %s \n\n with body %s \n\n with headers %s ",
        response.code(), response.message(), bodyString, response.headers());
    response = response
        .body(ResponseBody.create(response.body().contentType(), bodyString))

return response;

The main thing to remember is that one the response has been processed, you need to create a new one and return it.