Retrofit2.0添加Header的方法总结

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

(1)使用注解的方式添加一个header参数

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

(2)使用注解的方式添加多个header参数

public interface ApiService {  
    @Headers({
        "Accept: application/vnd.yourapi.v1.full+json",
        "User-Agent: YourAppName"
    })
    @GET("/data/{user_id}")
    Call getData(@Path("user_id") long userId);
}

(3)使用注解的方式,header参数每次都不同,动态添加header

public interface ApiService {  
    @GET("/data")
    Call> 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();

你可能感兴趣的:(Rxjava)