Retrofit,Okhttp对每个Request统一动态添加header和参数(五)

文/Tamic 个人公众号:开发者技术前线 (覆盖8W读者)
地址:http://blog.csdn.net/sk719887916/article/details/52189602

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

    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", "your-actual-api-key")
                .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缓存,统一对有无网络处理, 返回结果问题

  • Rxjava +Retrofit 如何优雅的取消网路请求

更多原创关注 个人公众号:开发者技术前线 (覆盖8W读者)

Retrofit,Okhttp对每个Request统一动态添加header和参数(五)_第1张图片

你可能感兴趣的:(Retrofit,Android进阶,网络编程,+Rx,实践及源码大全)