How to log request and response body with Retrofit-Android?

前端 未结 9 2064
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:35

I can\'t find relevant methods in the Retrofit API for logging complete request/response bodies. I was expecting some help in the Profiler (but it only offers meta-data abou

9条回答
  •  Happy的楠姐
    2020-11-28 22:02

    below code is working for both with header and without header to print log request & response. Note: Just comment .addHeader() line if are not using header.

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    //.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                    .addNetworkInterceptor(new Interceptor() {
    
                        @Override
    
                        public okhttp3.Response intercept(Chain chain) throws IOException {
                            Request request = chain.request().newBuilder()
                                    // .addHeader(Constant.Header, authToken)
                                       .build();
                            return chain.proceed(request);
                        }
                    }).build();
    
            final Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Constant.baseUrl)
                    .client(client) // This line is important
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    

提交回复
热议问题