Retrofit2.0添加Header的方法总结(推荐)

 更新时间:2018年09月30日 14:36:59   作者:PennTsui  
这篇文章主要介绍了Retrofit2.0添加Header的方法总结(推荐),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

最近在项目里面需要添加header,然后就想大家分想一下retrofit添加header的方法

(1)使用注解的方式添加一个header参数

public interface ApiService { 
  @Headers("Cache-Control: max-age=560000")
  @GET("/data")
  Call<List<Data>> getData();
} 

(2)使用注解的方式添加多个header参数

public interface ApiService { 
  @Headers({
    "Accept: application/vnd.yourapi.v1.full+json",
    "User-Agent: YourAppName"
  })
  @GET("/data/{user_id}")
  Call<Data> getData(@Path("user_id") long userId);
} 

(3)使用注解的方式,header参数每次都不同,动态添加header

public interface ApiService { 
  @GET("/data")
  Call<List<Data>> getData(@Header("Content-Range") String contentRange);
} 

(4)在代码里添加header,需要使用拦截器

OkHttpClient.Builder client = new OkHttpClient.Builder(); 
client.addInterceptor(new Interceptor() { 
  @Override
  public Response intercept(Interceptor.Chain chain) throws IOException {
    Request original = chain.request();
    Request request = original.newBuilder()
      .header("User-Agent", "YourAppName")
      .header("Accept", "application/vnd.yourapi.v1.full+json")
      .method(original.method(), original.body())
      .build();

    return chain.proceed(request);
  }
}

OkHttpClient httpClient = client.build(); 
Retrofit retrofit = new Retrofit.Builder() 
  .baseUrl(Constant.BASE_URL)
  .addConverterFactory(GsonConverterFactory.create())
  .client(httpClient)
  .build();

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

使用addNetworkInterceptor

当我们使用网络请求方面的拦截器时,直接使用addNetworkInterceptor方法来添加,而不要使用addInterceptor来添加。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

最新评论