Home > Java > javaTutorial > How to Implement HTTP Logging in Retrofit 2?

How to Implement HTTP Logging in Retrofit 2?

DDD
Release: 2024-12-14 05:32:13
Original
111 people have browsed it

How to Implement HTTP Logging in Retrofit 2?

Logging in Retrofit 2

In Retrofit 2, logging has been enhanced by providing more control over the level of detail in the logs. To enable logging, you can use the HttpLoggingInterceptor.

Implementation:

  1. Add the dependency to your build.gradle file:

    implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
    Copy after login
  2. Create a HttpLoggingInterceptor and specify the desired logging level:

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.level(HttpLoggingInterceptor.Level.BODY);
    Copy after login
  3. Create an OkHttpClient and add the interceptor:

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
    Copy after login
  4. Use the OkHttpClient to build your Retrofit instance:

    Retrofit retrofit = new Retrofit.Builder()
     .baseUrl("https://backend.example.com")
     .client(client)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
    Copy after login

With this setup, you will get detailed logs in your logcat, including the exact JSON payload sent in the request.

The above is the detailed content of How to Implement HTTP Logging in Retrofit 2?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template