背景
开发中,有时需要核对接口请求和响应参数,需要看到详细的接口调用。本来可以通过Facebook Stetho来监控接口的,但是受限于网络,导致调测界面打不开,所以只要寻求其他方案。
解决方案
通过okhttp添加拦截器,打印接口调用日志。
- 添加依赖
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' - 添加拦截器
- kotlin写法
val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
Log.d("HttpLogInfo", message)
})
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
okHttpBuilder.addInterceptor(loggingInterceptor)
- java写法
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("HttpLogInfo", message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpBuilder.addInterceptor(loggingInterceptor);
- 打印出的日志样例:
- 如果想要格式化输出的消息格式,可以参考《利用logger打印完整的okhttp网络请求和响应日志》
安卓开发技术分享: https://blog.csdn.net/yinxing2008/article/details/84555061