Retrofit 2.x : Log Header for request and response

后端 未结 5 1447
傲寒
傲寒 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:20

    Oh I found the error if anyone is interested :

     HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder()
                            .addHeader("key", "value")
                            .addHeader("HEADER","HEADER Value")
                            .build();
                    return chain.proceed(request);
                }
    
    
            }).build();
    

    You must add the log interceptor (your interceptor variable) after the request interceptor, so the correct answer is:

     HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws 
     IOException {
                    Request request = chain.request().newBuilder()
                            .addHeader("key", "value")
                            .addHeader("HEADER","HEADER Value")
                            .build();
                    return chain.proceed(request);
                }
    
    
            })
            .addInterceptor(interceptor)
            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .build();
    

提交回复
热议问题