分类:
作者同类文章
X
版权声明:本文为博主原创文章,未经博主允许不得转载。
用过retrofit的同学,肯定会很爽,因为用起来实在是方便。但是我之前在使用retrofit的时候,发现没法打印出网络请求日志,包括请求urll、返回内容等。要实现打印日志,就要用到HttpLoggingInterceptor这个类。下面给大家讲一下如何打印出这些内容。
步骤
1、导入库
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
- 1
- 2
- 3
2、初始化HttpLoggingInterceptor
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//打印retrofit日志
Log.i("RetrofitLog","retrofitBack = "+message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
3、配置okhttp
client = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(loggingInterceptor)
.connectTimeout(mTimeOut, TimeUnit.SECONDS)
.readTimeout(mTimeOut, TimeUnit.SECONDS)
.writeTimeout(mTimeOut, TimeUnit.SECONDS)
.build();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4、配置retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(userCenter)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
- 1
- 2
- 3
- 4
- 5
- 6
日志级别
大家看到配置loggingInterceptor的时候
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
- 1
类型为BASIC,其实日志级别分为4类:NONE、BASIC、HEADERS、BODY。
大家看下我打印出来的日志,就知道这4类的区别了。
1、NONE
没有任何log
- 1
2、BASIC
请求/响应行
basic的格式:
--> POST 地址 http/1.1 (0-byte body)
<-- 200 OK 地址 (154ms, unknown-length body)
- 1
- 2
- 3
3、HEADERS
请求/响应行 + 头
4、BODY
请求/响应行 + 头 + 体
-
顶
- 2
-
踩
- 0