Adding header to all request with Retrofit 2

前端 未结 10 1423
北荒
北荒 2020-11-29 17:46

Retrofit 2\'s documentation says:

Headers that need to be added to every request can be specified using an OkHttp interceptor.

I

10条回答
  •  我在风中等你
    2020-11-29 18:18

    For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1

     public OkHttpClient getHeader(final String authorizationValue ) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient okClient = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .addNetworkInterceptor(
                            new Interceptor() {
                                @Override
                                public Response intercept(Interceptor.Chain chain) throws IOException {
                                    Request request = null;
                                    if (authorizationValue != null) {
                                        Log.d("--Authorization-- ", authorizationValue);
    
                                        Request original = chain.request();
                                        // Request customization: add request headers
                                        Request.Builder requestBuilder = original.newBuilder()
                                                .addHeader("Authorization", authorizationValue);
    
                                        request = requestBuilder.build();
                                    }
                                    return chain.proceed(request);
                                }
                            })
                    .build();
            return okClient;
    
        }
    

    Now in your retrofit object add this header in the client

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(getHeader(authorizationValue))
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    

提交回复
热议问题