Home >Java >javaTutorial >How to Log Retrofit 2 Request and Response Bodies?

How to Log Retrofit 2 Request and Response Bodies?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 19:35:10166browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn