Retrofit配置headers无效的可能原因

操作一个Retrofit的步骤一般是这样的

  • 创建一个网络拦截器,添加一些通用的headers
Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .addHeader("xxx", "xxx")
                        .addHeader("xxx", "xxx")
                        .addHeader("Content-Type", "application/json")
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        };
  • 创建一个打印请求日志的拦截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(BuildConfig.DEBUG ? 
                HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
  • 在OKHttpClient中加入创建的拦截器
OkHttpClient okHttpClient= new OkHttpClient.Builder()
                .addInterceptor(interceptor) // 添加headers拦截器
                .addInterceptor(mHttpLoggingInterceptor)// 添加log拦截器
                .readTimeout(8000, TimeUnit.MILLISECONDS)
                .writeTimeout(8000, TimeUnit.MILLISECONDS)
                .build();

其实我们看上面的addInterceptor方法好像是并列的,至于哪个拦截器在前,哪个在后,应该无所谓。但是事实是,如果吧mHttpLoggingInterceptor放前面,则后面的interceptor添加的heanders将不会生效。当我们使用addInterceptor来添加网络拦截器时,一定要把网络拦截器放前面

  • 使用addNetworkInterceptor
    当我们使用网络请求方面的拦截器时,直接使用addNetworkInterceptor方法来添加,而不要使用addInterceptor来添加。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Retrofit是squareup公司的开源力作,和同属squareup公司开源的OkHttp,一个负责网络调度,...
    蓝灰_q阅读 42,020评论 23 281
  • 什么是 Retrofit ? Retrofit是Square开发的一个Android和Java的REST客户端库。...
    帅气的猪猪阅读 5,357评论 0 0
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,480评论 2 59
  • 1、活动指示器 活动指示器表明进程或任务正在进行中 (1)当任务加载和进行时旋转,任务完成后自动消失(针对系统默认...
    Ronie阅读 7,964评论 0 29
  • 蝉收敛起一生的歌喉 蟋蟀鼓动双手 一丝凉风 惊动一颗熟睡地露珠 叮咚一声 诗意般滑落 从一片沉淀过烈日的绿...
    星空物语_07f5阅读 734评论 0 0