Android Retrofit2&OkHttp3添加统一的请求头Header

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

在使用Retrofit时,有时候需要设置Set-Cookie等请求头,如果每一个url都需要,那么直接来个拦截器就好了。

官方说明:

 
     
  • OkHttp3下OkHttpClient的  List< Interceptor>  interceptors()方法,返回的是一个不可编辑的列表,如果对其进行编辑会报出UnSupportedOperationException
  •  
  • Interceptor的典型使用场景,就是对request和response的Headers进行编辑
  •  

如下图所示:

Android Retrofit2&OkHttp3添加统一的请求头Header_第1张图片

注意Header头,不要照抄,要灵活运用。

让所有网络请求都附上你的 token:

Interceptor mTokenInterceptor = new Interceptor() {    @Override public Response intercept(Chain chain) throws IOException {        Request originalRequest = chain.request();        if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {            return chain.proceed(originalRequest);        }        Request authorised = originalRequest.newBuilder()            .header("Authorization", Your.sToken)            .build();        return chain.proceed(authorised);    }};
    
    
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

为OkHttpClient 添加两个以上的拦截器,如下代码所示:

public class RestDataSource implements Repository {    private final MarvelService mMarvelService;    @Inject    public RestDataSource() {        // Log信息        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);        // 公私密匙        MarvelSigningInterceptor signingInterceptor = new MarvelSigningInterceptor(                BuildConfig.MARVEL_PUBLIC_KEY, BuildConfig.MARVEL_PRIVATE_KEY);        // OkHttp3.0的使用方式        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(signingInterceptor)                .addInterceptor(loggingInterceptor)                .build();        // 选择人物信息        Gson customGsonInstance = new GsonBuilder()                .registerTypeAdapter(new TypeToken>() {                        }.getType(),                        new MarvelResultsDeserializer())                .create();        // 适配器        Retrofit marvelApiAdapter = new Retrofit.Builder()                .baseUrl(MarvelService.END_POINT)                .addConverterFactory(GsonConverterFactory.create(customGsonInstance))                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .client(client)                .build();        // 服务        mMarvelService = marvelApiAdapter.create(MarvelService.class);    }    // 返回人物信息    @Override    public Observable> getCharacters(int currentOffset) {        return mMarvelService.getCharacters(currentOffset);    }}
    
    
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

下面来个完整的配置:

import okhttp3.Interceptor;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;import retrofit2.Retrofit;public class RetrofitAPIManager {    public static final String SERVER_URL = "url";    public static ClientAPI provideClientApi() {        Retrofit retrofit = new Retrofit.Builder()                .baseUrl(SERVER_URL)                .client(genericClient())                .build();        return retrofit.create(ClientAPI.class);    }    public static OkHttpClient genericClient() {        OkHttpClient httpClient = new OkHttpClient.Builder()                .addInterceptor(new Interceptor() {                    @Override                    public Response intercept(Chain chain) throws IOException {                        Request request = chain.request()                                .newBuilder()                                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")                                .addHeader("Accept-Encoding", "gzip, deflate")                                .addHeader("Connection", "keep-alive")                                .addHeader("Accept", "*/*")                                .addHeader("Cookie", "add cookies here")                                .build();                        return chain.proceed(request);                    }                })                .build();        return httpClient;    }}
    
    
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

你可能感兴趣的:(Android Retrofit2&OkHttp3添加统一的请求头Header)