Retrofit 2. Use annotations to dynamically and statically add request headers

    Retrofit provides two methods for defining HTTP request header fields, static and dynamic. The static header cannot be changed to a different request. The key and value of the header are fixed and unchangeable. They are fixed as the program is opened. In Retrofit 2.0, OkHttp is required and automatically set as a dependency. In this way, we can add request headers by adding request headers by OkHttp.


Dynamically added

    @Header
    String value:默认为"",参数名称

    @GET("/")
    Call<ResponseBody> query(@Header("Accept-Language") String lang);

    @HeaderMap

    @GET("/search")
    Call<ResponseBody> query(@HeaderMap Ma<String, String> headers);

Statically added

@Headers("Cache-Control: max-age=640000")
@GET("/tasks")
Call<List<Task>> getTasks();

@Headers({
    "X-Foo: Bar",
    "X-Ping: Pong"
})
@GET("/")
Call(ResponseBody) deleteObject(@Query("id") String id);

OkHttp request interceptor

  OkHttpClient client = httpClient.build();      Retrofit retrofit = new Retrofit.Builder()          .baseUrl(API_BASE_URL)       .addConverterFactory(GsonConverterFactory.create())      .client(httpClient)        .build();
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  
        httpClient.addInterceptor(new Interceptor() {  
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Cache-Control", "no-cache")
                    .method(original.method(), original.body())
                    .build();

                return chain.proceed(request);
            }
    }

   

    OkHtt请求头通过拦截器添加Header,两种方式的不同
    .header(key, val):如果key相同,最后一个val会将前面的val值覆盖
    .addHeader(key, val):如果key相同,最后一个val不会将前面的val值覆盖,而是新添加一个Header

Guess you like

Origin blog.csdn.net/shu_quan/article/details/79878549