Home >Java >javaTutorial >How to Log Retrofit 2 Request and Response Bodies?
Logging Requests and Responses in Retrofit 2
In Retrofit 1, logging the exact JSON sent in a request was straightforward using setLog() and setLogLevel(). However, Retrofit 2 has since deprecated these methods, leaving developers wondering how to properly log network traffic.
Using HttpLoggingInterceptor
The solution lies in HttpLoggingInterceptor, which can be added to the OkHttpClient to log both request and response bodies:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Next, create a Retrofit object using the OkHttpClient with the added interceptor:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(...) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
Setting the logging level to BODY will provide detailed logs similar to those generated by setLogLevel(RestAdapter.LogLevel.FULL) in Retrofit 1.
Resolving ClassNotFoundException
If you encounter a java.lang.ClassNotFoundException, ensure that the version of logging-interceptor matches your Retrofit version. In some cases, older Retrofit versions may require an earlier logging-interceptor version.
The above is the detailed content of How to Log Retrofit 2 Request and Response Bodies?. For more information, please follow other related articles on the PHP Chinese website!