栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

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

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

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

public interface ApiService { 
  @GET("/data")
  Call> 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来添加。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/155469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号