Retrofit 2.x : Log Header for request and response

后端 未结 5 1449
傲寒
傲寒 2021-02-13 03:17

I am using retrofit 2.x and i want to log the header and body of request and response .

  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            


        
5条回答
  •  鱼传尺愫
    2021-02-13 03:38

    The following link was very useful: https://medium.com/swlh/okhttp-interceptors-with-retrofit-2dcc322cc3f3

    OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
    
    //Gson Builder
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    Timber.plant(new Timber.DebugTree());
    
    // HttpLoggingInterceptor
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -> Timber.i(message));
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    
    
    /**
     * injection of interceptors to handle encryption and decryption
     */
    
    //Encryption Interceptor
    EncryptionInterceptor encryptionInterceptor = new EncryptionInterceptor(new EncryptionImpl());
    //Decryption Interceptor
    DecryptionInterceptor decryptionInterceptor = new DecryptionInterceptor(new DecryptionImpl());
    
    
    // OkHttpClient. Be conscious with the order
    OkHttpClient okHttpClient = new OkHttpClient()
        .newBuilder()
        //httpLogging interceptor for logging network requests
        .addInterceptor(httpLoggingInterceptor)
        //Encryption interceptor for encryption of request data
        .addInterceptor(encryptionInterceptor)
        // interceptor for decryption of request data
        .addInterceptor(decryptionInterceptor)
        .build();
    
    //Retrofit
    Retrofit retrofit = new Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(BASE_URL)
        // for serialization
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();
    
    //ApiService
    apiService = retrofit.create(ApiService.class);
    

提交回复
热议问题