Logging with Retrofit 2

前端 未结 21 1667
春和景丽
春和景丽 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:00

    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.

提交回复
热议问题