1. 程式人生 > >Retrofit,Okhttp對每個Request統一動態新增header和引數(五)

Retrofit,Okhttp對每個Request統一動態新增header和引數(五)

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結合系列請閱讀: