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();
client.setFollowRedirects(false);
client.setFollowSslRedirects(false);
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);
/** DEBUG STUFF */
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
.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
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.
HTH,
Member discussion: