Logging with Retrofit 2

前端 未结 21 1321
春和景丽
春和景丽 2020-11-22 07:33

I\'m trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHt         


        
21条回答
  •  伪装坚强ぢ
    2020-11-22 08:19

    I was also stuck in similar kind of situation, setLevel() method was not coming, when I was trying to call it with the instance of HttpLoggingInterceptor, like this:

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    

    Here is how I resolved it, to generate log for Retrofit2,

    I suppose you have added the dependecy,

    implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"
    

    For the latest version you can check out, this link:

    https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor )

    Here they have also explained about how to add.

    I created a class with name AddLoggingInterceptor, here is my code,

    public class AddLoggingInterceptor {
    
        public static OkHttpClient setLogging(){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .build();
    
            return okHttpClient;
        }
    }
    

    Then, where we are instantiating our Retrofit,

     public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(AddLoggingInterceptor.setLogging()) // here the method is called inside client() method, with the name of class, since it is a static method.
                    .build();
        }
        return retrofit;
    }
    

    Now you can see log generated in your Android Studio, you may need to search, okHttp for filtering process. It worked for me. If any issues you can text me here.

提交回复
热议问题