RxJava+Retrofit2.0 OkHttp添加日志拦截器和设置请求头

添加日志拦截器

<code>
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
//DEBUG模式下 添加日志拦截器
if(BuildConfig.DEBUG){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClientBuilder.addInterceptor(interceptor);
}
</code>

设置请求头

<code>
//添加一个设置header拦截器
//设备系统/app版本号(设备的系统版本号;设备型号)
httpClientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request mRequest = chain.request().newBuilder()
.header(“User-Agent”,”android/” + App.VERSIONNAME + “(” + DeviceUtils.getSDKVersion() + “;” + DeviceUtils.getModel() + “)”)
.build();
return chain.proceed(mRequest);
}
});
</code>
最后添加到retrofit中
mRetrofit = new Retrofit.Builder().client(httpClientBuilder.build())

    原文作者:Derek_Yan
    原文地址: https://www.jianshu.com/p/aa12be131d7e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞