文/Tamic
地址:http://tamicer.com
How to Add header to Every Request
添加统一通用header, 不会覆盖前面的header
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| okHttpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .addHeader("header-key", "value1") .addHeader("header-key", "value2"); Request request = requestBuilder.build(); return chain.proceed(request); } });
|
添加统一通用header, 会覆盖前面的header
1 2 3 4 5 6 7 8 9 10 11 12 13
| okHttpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .header("headerkey", "header-value"); Request request = requestBuilder.build(); return chain.proceed(request); } });
|
Parameters
How to Add Query Parameters to Every Request
拦截器Interceptor,是okhttp的一大特点,后续我会对他进行介绍
拦截器添加参数用 addQueryParameter()
函式来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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.Builder requestBuilder = original.newBuilder() .url(url); Request request = requestBuilder.build(); return chain.proceed(request); } });
|
Retrofit+RxJava结合系列请阅读:
第一时间获资讯请关注微信公众号!