一、使用注解
1. 添加单个header
public interface ApiService {
@Headers("Content-Type: application/javascript")
@GET("/data")
Call<List<Data>> getData();
}
2. 添加多个header
public interface ApiService {
@Headers({
"Content-Type: application/javascript",
"User-Agent: YourAgent"
})
@GET("/data/{user_id}")
Call<List<Data>> getData();
}
3. 动态添加header
public interface ApiService {
@GET("/data")
Call<List<Data>> getData(@Header("Content-Range") String contentRange);
}
二、如果要添加全局header,则需要在代码中添加header
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("X-Requested-With", "XMLHttpRequest")
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36")
.build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
网友评论