(1)使用注解的方式
添加一个Header参数
publicinterfaceUserService {
@Headers("Cache-Control: max-age=640000")
@GET("/tasks")
Call> getTasks();
}
添加多个Header参数
publicinterfaceUserService {
@Headers({
"Accept: application/vnd.yourapi.v1.full+json",
"User-Agent: Your-App-Name"
})
@GET("/tasks/{task_id}")
Call getTask(@Path("task_id")longtaskId);
}
(2)使用代码的方式,则需要使用拦截器
OkHttpClient.Builder httpClient =newOkHttpClient.Builder();
httpClient.addInterceptor(newInterceptor() {
@Override
publicResponse intercept(Interceptor.Chain chain)throwsIOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent","Your-App-Name")
.header("Accept","application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
returnchain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit =newRetrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
(3)使用注解的方式,但是Header参数每次提交的都不同,也就是动态的Header
publicinterfaceUserService {
@GET("/tasks")
Call> getTasks(@Header("Content-Range") String contentRange);
}
注意:以上都是在Retrofit2.0及以上使用的。