Home  >  Q&A  >  body text

android - retrofit怎么针对不同的url统一添加header?

目前我是使用retrofit来作为我的网络请求框架,对某些请求还需要加headers。我在官网查到有@Header标签来指定header参数,但是这样写的话太繁琐,如果service中方法比较多的话,不是要写死了。又在网上又查了下,可以使用自定义的OkHttpClient来实现,然后使用:

Retrofit retrofit = new Retrofit.Builder()  
            .baseUrl(SERVER_URL)  
            .client(genericClient())  
            .build();

但是这种做法的话,就会把所有使用这个retrofit的url都加上了header,但是部分url是不需要的,比如我只是想在需要授权的url调用上都加上header参数(header里面加token)。找了半天网上没有相关的文章,所以请SF的朋友们回答下,谢谢!

PHP中文网PHP中文网2764 days ago591

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 17:37:36

    This is what I wrote

    OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException, java.io.IOException {
            Request request = chain.request().newBuilder()
                    .addHeader("Source", "android")
                    .addHeader("Accept", "application/json,text/javascript,*/*")
                    .build();
            return chain.proceed(request);
        }
    });
    OkHttpClient client = builder.build();
    
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_TRC_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(getGson()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    

    But you can’t add tokens all at once

    reply
    0
  • Cancelreply