欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

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

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

(2)使用注解的方式添加多個(gè)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ù)每次都不同,動(dòng)態(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();

其實(shí)我們看上面的addInterceptor方法好像是并列的,至于哪個(gè)攔截器在前,哪個(gè)在后,應(yīng)該無所謂。但是事實(shí)是,如果吧mHttpLoggingInterceptor放前面,則后面的interceptor添加的heanders將不會(huì)生效。當(dāng)我們使用addInterceptor來添加網(wǎng)絡(luò)攔截器時(shí),一定要把網(wǎng)絡(luò)攔截器放前面。

使用addNetworkInterceptor

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

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

相關(guān)文章

最新評論