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?
With a HttpLoggingInterceptor, OkHttp will automatically log incoming and outgoing HTTP requests and responses to Logcat, where we can then see information like the type of request, the fully resolved URL, the content-type, the different HTTP headers, and the payload of the body itself, which contains the actual JSON, ...
Android OkHttp Logging interceptor Interceptors are used to intercept OkHttp calls. The reason to intercept could be to monitor, rewrite and retry calls. It can be used for outgoing request or incoming response both.
In Retrofit 2 you should use HttpLoggingInterceptor.
Add dependency to build.gradle
. Latest version as of October 2019 is:
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
Create a Retrofit
object like the following:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://backend.example.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(ApiClient.class);
In case of deprecation warnings, simply change setLevel
to:
interceptor.level(HttpLoggingInterceptor.Level.BODY);
The above solution gives you logcat messages very similar to the old ones set by
setLogLevel(RestAdapter.LogLevel.FULL)
In case of java.lang.ClassNotFoundException
:
Older Retrofit version might require an older logging-interceptor
version. Take a look at comments sections for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With