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

文/Tamic

地址: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结合系列请阅读:

上一篇:孤荷凌寒自学python第五十八天成功使用python来连接上远端MongoDb数据库


下一篇:Selenium启动项参数设置