Summary of of Recommendations for Adding Header to Retrofit 2.0

  • 2021-10-16 02:40:09
  • OfStack

Recently, we need to add header in the project, and then we want to think about the method of adding header to retrofit

(1) Add an header parameter using annotations


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

(2) Adding multiple header parameters using annotations


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) In the way of annotation, header parameters are different every time, and header is added dynamically


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

(4) To add header to your code, you need to use an interceptor


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();

In fact, we look at the above addInterceptor methods as if they are juxtaposed. It doesn't matter which interceptor is in front and which is behind. But the fact is, if you put mHttpLoggingInterceptor in front, the heanders added by the following interceptor will not take effect. When we use addInterceptor to add a network interceptor, 1 must put the network interceptor first.

Use addNetworkInterceptor

When we use interceptors for network requests, use the addNetworkInterceptor method directly instead of addInterceptor.


Related articles: