亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Retrofit2.0添加Header的方法總結(jié)(推薦)

 更新時間:2018年09月30日 14:36:59   作者:PennTsui  
這篇文章主要介紹了Retrofit2.0添加Header的方法總結(jié)(推薦),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

(1)使用注解的方式添加一個header參數(shù)

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

(2)使用注解的方式添加多個header參數(shù)

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參數(shù)每次都不同,動態(tài)添加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方法好像是并列的,至于哪個攔截器在前,哪個在后,應(yīng)該無所謂。但是事實是,如果吧mHttpLoggingInterceptor放前面,則后面的interceptor添加的heanders將不會生效。當我們使用addInterceptor來添加網(wǎng)絡(luò)攔截器時,一定要把網(wǎng)絡(luò)攔截器放前面。

使用addNetworkInterceptor

當我們使用網(wǎng)絡(luò)請求方面的攔截器時,直接使用addNetworkInterceptor方法來添加,而不要使用addInterceptor來添加。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論