怎么在Retrofit2.0中添加Header

怎么在Retrofit2.0中添加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();

看完上述内容,你们掌握怎么在Retrofit2.0中添加Header的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!