Retrofit 2.0 对Okhttp每个Request统一添加header和Parameter(五)

文/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
    超能实践,完美支持Https传输

  • Retrofit2.0
    完美同步Cookie实现免登录

  • Retrofit 2.0 超能实践(三),轻松实现文件/图片上传

  • -Retrofit 2.0 超能实践(四),完成大文件断点下载

  • 基于Retrofit2.0 封装的超好用的RetrofitClient工具类

  • 玩转IOC,教你徒手实现自定义的Retrofit框架

  • Rxjava +Retrofit 你需要掌握的几个技巧,Retrofit缓存,统一对有无网络处理, 返回结果问题

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

开发者技术前线

你可能感兴趣的:(Retrofit 2.0 对Okhttp每个Request统一添加header和Parameter(五))