I'm trying to get the exact JSON that is being sent in the request. Here is my code:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
@Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
request.body().toString(), request.headers()));
com.squareup.okhttp.Response response = chain.proceed(request);
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client).build();
But I only see this in the logs:
request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
How am I supposed to do proper logging, given the removal of setLog()
and setLogLevel()
which we used to use with Retrofit 1?
Here is an
Interceptor
that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):for Retrofit 2.0.2 the code is like
A best way to do this right in Retrofit 2 is to add the logger interceptor as a networkInterceptor this will print out the network headers and your custom headers too. The important thing is to remember that interceptor work as a stack and be sure u add the logger at the end of all.
You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/
Then open "chrome://inspect" in Chrome...
this will create a retrofit object with Logging. without creating separate objects.
The main problem which I faced was dynamical adding headers and logging them into debug logcat. I've tried to add two interceptors. One for logging and one for adding headers on-the-go (token authorization). The problem was that we may .addInterceptor or .addNetworkInterceptor. As Jake Wharton said to me: "Network interceptors always come after application interceptors. See https://github.com/square/okhttp/wiki/Interceptors". So here is working example with headers and logs: