Retrofit2.0 添加log拦截公共参数
Posted xiaoqiang_0719
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit2.0 添加log拦截公共参数相关的知识,希望对你有一定的参考价值。
创建retrofit 进行网络请求
Retrofit retrofit = new Retrofit.Builder().client(getOkHttpClient())//使用自己创建的OkHttp
.baseUrl("http://fy.iciba.com/") // 设置 网络请求 Url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
.build();
主要工作都在getOkHttpClient 方法中,实现实现log拦截器以及参数添加拦截器
private OkHttpClient getOkHttpClient() //获取log拦截器 HttpLoggingInterceptor logger = getLogger(); //定制OkHttp OkHttpClient.Builder httpClientBuilder = new OkHttpClient .Builder(); //OkHttp进行添加拦截器loggingInterceptor 打印log httpClientBuilder.addInterceptor(logger); //获取公共参数添加拦截器 HeadInterceptor headInterceptor = new HeadInterceptor( "head"); //OkHttp进行添加拦截器headInterceptor添加公共参数 httpClientBuilder.addInterceptor(headInterceptor); return httpClientBuilder.build();
再看getLogger方法,将okhttp请求log信息以Tag=xiaoqiang打印出来
public HttpLoggingInterceptor getLogger()
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger()
@Override
public void log(String message)
Log.d("xiaoqiang", "OkHttp====:" + message);
);
loggingInterceptor.setLevel(level);
return loggingInterceptor;
添加公共请求参数,实现Interceptor接口
public class HeadInterceptor implements Interceptor
private final String Head;
public HeadInterceptor(String head)
Head = head;
@Override
public Response intercept(Interceptor.Chain chain) throws IOException
Request oldRequest = chain.request();
// 添加新的参数
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host())
.addQueryParameter("Head", Head)
.addQueryParameter("token", "123456789");
// 新的请求
Request newRequest = oldRequest.newBuilder()
.method(oldRequest.method(), oldRequest.body())
.url(authorizedUrlBuilder.build())
.build();
return chain.proceed(newRequest);
结果可以看到log会正常打印并且参数Head 和token会作为参数添加到请求中
结果如下:
以上是关于Retrofit2.0 添加log拦截公共参数的主要内容,如果未能解决你的问题,请参考以下文章
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Android Retrofit2 0 查看log和JSON字符串(HttpLoggingInterceptor)