Retrofit2.0+OkHttp打印Request URL(请求地址参数)

时间:2022-07-22 19:57:56

学习了Retrofit中的拦截器功能:实现日志中打印请求头内容

Retrofit 2+ 是基于OKHttp进行封装的,那么也就是说想进行请求拦截然后进行打印出来的话,就必须要从OkHttp进行入手。

1,添加依赖包:

compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'

2,我这里是新建了一个方法进行创建并获取OkHttp

private OkHttpClient getOkHttpClient() {
//日志显示级别
HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("zcb","OkHttp====Message:"+message);
}
});
loggingInterceptor.setLevel(level); //定制OkHttp
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
.Builder();
//OkHttp进行添加拦截器loggingInterceptor
httpClientBuilder.addInterceptor(loggingInterceptor);
return httpClientBuilder.build();
}

3,把获取到的OkHttp给Retrofit进行使用

Retrofit retrofit=new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient())//使用自己创建的OkHttp
.build();

效果图:我发起了三个请求。

Retrofit2.0+OkHttp打印Request URL(请求地址参数)

参考资料:

OKHttp源码解析

OkHttp源码:Logging Interceptor

学会Retrofit+OkHttp+RxAndroid三剑客的使用,让自己紧跟Android潮流的步伐