美文网首页移动潮流技术网络请求Rx系列
Retrofit 2.0 对Okhttp每个Request统一添

Retrofit 2.0 对Okhttp每个Request统一添

作者: Tamic | 来源:发表于2016-08-12 20:01 被阅读3526次

    文/Tamic
    地址:http://www.jianshu.com/p/b1979c25634f

    今天的内容主要依靠OKHTTP的拦截器:
    OKHttp原理请看我写的这个系列:
    OkHttp 3.x 源码解析之Interceptor 拦截器

    Header

    How to Add header to Every Request

    添加统一通用header, 不会覆盖前面的header

    okHttpClient.interceptors().add(new Interceptor() {  
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
    
            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                        .addHeader("header-key", "value1")
                        .addHeader("header-key", "value2");
    
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    

    添加统一通用header, 会覆盖前面的header

    okHttpClient.interceptors().add(new Interceptor() {  
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
    
            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("headerkey", "header-value"); // <-- this is the important line
    
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    

    Parameters

    How to Add Query Parameters to Every Request

    拦截器添加参数用 addQueryParameter()函式来实现。

        OkHttpClient.Builder httpClient =  
        new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {  
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            HttpUrl originalHttpUrl = original.url();
    
            HttpUrl url = originalHttpUrl.newBuilder()
                    .addQueryParameter("apikey", "you value")
                    .build();
    
            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .url(url);
    
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    

    Retrofit+RxJava结合系列请阅读:

    第一时间获取技术文章请关注微信公众号!

    开发者技术前线

    相关文章

      网友评论

      本文标题:Retrofit 2.0 对Okhttp每个Request统一添

      本文链接:https://www.haomeiwen.com/subject/usjesttx.html