使用拦截器添加标头的Android Retrofit 2.0不起作用

我有用于OkHttp客户端的Singleton dagger模块,我正在尝试使用Interceptor添加标头

@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache, final LocalData localData) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(logging);
    client.addNetworkInterceptor(new Interceptor() {
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Hp-Application", "Android");
            Request request = requestBuilder.build();
            Response originalResponse = chain.proceed(request);
            try {
                if (originalResponse.code() == 200) {
                    localData.setLastUpdateTime(System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return originalResponse;
        }
    });
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.cache(cache);
    return client.build();
}

但看着日志我看不到预期的标题.此外,我收到错误,因为没有必要的标题,特定的调用不起作用.

我还尝试使用不同的类添加addInterceptor()/ addNetworkInterceptor()

 public class HeaderInterceptor
        implements Interceptor {
    @Override
    public Response intercept(Chain chain)
            throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader("Hp-Application", "Android")
                .build();
        return chain.proceed(request);
    }
}

但这种方式对我来说也不起作用.

如何在每次只有一个实现的应用程序调用中添加此标头?

解决方法:

添加拦截器的顺序很重要.您的日志记录拦截器首先运行,然后才会运行标头添加拦截器.

为了获得最佳的日志记录体验,请将日志记录拦截器设置为您添

上一篇:【MyBatis框架】MyBatis入门程序第一部分


下一篇:java – 自动连接到休眠拦截器