Logging with Retrofit 2

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

    The main problem which I faced was dynamical adding headers and logging them into debug logcat. I've tried to add two interceptors. One for logging and one for adding headers on-the-go (token authorization). The problem was that we may .addInterceptor or .addNetworkInterceptor. As Jake Wharton said to me: "Network interceptors always come after application interceptors. See https://github.com/square/okhttp/wiki/Interceptors". So here is working example with headers and logs:

    OkHttpClient httpClient = new OkHttpClient.Builder()
                //here we can add Interceptor for dynamical adding headers
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().addHeader("test", "test").build();
                        return chain.proceed(request);
                    }
                })
                //here we adding Interceptor for full level logging
                .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(httpClient)
                .baseUrl(AppConstants.SERVER_ADDRESS)
                .build();
    

提交回复
热议问题