Retrofit,Okhttp对每个Request统一动态添加header和参数
Posted Tamic大白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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结合系列请阅读:
更多原创关注 个人公众号:开发者技术前线 (覆盖8W读者)
以上是关于Retrofit,Okhttp对每个Request统一动态添加header和参数的主要内容,如果未能解决你的问题,请参考以下文章
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Android OkHttp + Retrofit 取消请求的方法