Retrofit 2.0 对Okhttp每个Request统一添
2016-08-12 本文已影响3526人
Tamic
文/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结合系列请阅读:
第一时间获取技术文章请关注微信公众号!
开发者技术前线