Android改装添加标头以及HttpLoggingInterceptor

时间:2018-10-15 08:06:15

标签: android retrofit

我目前正在研究android中的改造:

这是我当前的代码:

 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 newRequest  = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
                    .build();
            return chain.proceed(newRequest);
        }
    }).build();

如何将HttpLoggingInterceptor添加到客户端,同时又将标头添加到客户端?

2 个答案:

答案 0 :(得分:0)

要在Retrofit中添加拦截器,请在构建OkHttpClient时将其包括在内,

OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new HttpLoggingInterceptor())

然后您使用此客户端构建Retrofit

Retrofit.Builder builder = new Retrofit.Builder()
                .client(client);

Retrofit retrofit = builder.build();

答案 1 :(得分:0)

您可以添加两次调用方法addInterceptor的两个拦截器:

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 newRequest = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
                    .build();
                return chain.proceed(newRequest);
            }
        })
   .addInterceptor(interceptor).build();