最近在项目里面需要添加header,然后就想大家分想一下retrofit添加header的方法
(1)使用注解的方式添加一个header参数
1
2
3
4
5
|
public interface ApiService { @Headers ( "Cache-Control: max-age=560000" ) @GET ( "/data" ) Call<List<Data>> getData(); } |
(2)使用注解的方式添加多个header参数
1
2
3
4
5
6
7
8
|
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
1
2
3
4
|
public interface ApiService { @GET ( "/data" ) Call<List<Data>> getData( @Header ( "Content-Range" ) String contentRange); } |
(4)在代码里添加header,需要使用拦截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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(); |
其实我们看上面的addInterceptor方法好像是并列的,至于哪个拦截器在前,哪个在后,应该无所谓。但是事实是,如果吧mHttpLoggingInterceptor放前面,则后面的interceptor添加的heanders将不会生效。当我们使用addInterceptor来添加网络拦截器时,一定要把网络拦截器放前面。
使用addNetworkInterceptor
当我们使用网络请求方面的拦截器时,直接使用addNetworkInterceptor方法来添加,而不要使用addInterceptor来添加。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/silenceoo/article/details/77460607