背景
用过retrofit的同学,肯定会很爽,因为用起来实在是方便。但是我之前在使用retrofit的时候,发现没法打印出网络请求日志,包括请求urll、返回内容等。要实现打印日志,就要用到HttpLoggingInterceptor这个类。下面给大家讲一下如何打印出这些内容。
步骤:
依赖库 : 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'
方式一
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);
3、配置okhttp
client = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(loggingInterceptor)
.connectTimeout(mTimeOut, TimeUnit.SECONDS)
.readTimeout(mTimeOut, TimeUnit.SECONDS)
.writeTimeout(mTimeOut, TimeUnit.SECONDS)
.build();
4、配置retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(userCenter)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
日志级别
大家看到配置loggingInterceptor的时候
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
类型为BASIC,其实日志级别分为4类:NONE、BASIC、HEADERS、BODY。
大家看下我打印出来的日志,就知道这4类的区别了。
1、NONE
没有任何log
2、BASIC
请求/响应行
basic的格式:
--> POST 地址 http/1.1 (0-byte body)
<-- 200 OK 地址 (154ms, unknown-length body)
3、HEADERS
请求/响应行 + 头
4、BODY
请求/响应行 + 头 + 体
方式二:使用 Interceptor 拦截器
public class ParamsLogInterceptor implements Interceptor {
private static final String TAG = "ParamsLogInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
okhttp3.Response response = chain.proceed(chain.request());
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.e(TAG, "请求地址:" + request.toString());
printParams(request.body());
Log.e(TAG, "请求体返回:| Response:" + content);
Log.e(TAG, "----------请求耗时:" + duration + "毫秒----------");
return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
}
private void printParams(RequestBody body) {
Buffer buffer = new Buffer();
try {
body.writeTo(buffer);
Charset charset = Charset.forName("UTF-8");
MediaType contentType = body.contentType();
if (contentType != null) {
charset = contentType.charset(UTF_8);
}
String params = buffer.readString(charset);
Log.e(TAG, "请求参数: | " + params);
} catch (IOException e) {
e.printStackTrace();
}
}