okhttp3 添加日志拦截器


最近在使用Retrofit时,因为想把请求报文与响应报文的具体内容打到Monitor中,以便于与服务器进行联调。现在进行总结一下


  1. 使用开源Log管理工具,在Studio中添加如下依赖。
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'

然后在网络基类中添加如下代码(前提是使用okhttp 或是 retrofit)

 // Log信息拦截器
 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
 //设置日志打印级别
 loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
 //将拦截器添加到ok中
 builder.addInterceptor(loggingInterceptor);

只需要这三行代码就可实现日志的打印。关于这种方式,经过测试会出现在有些手机上无法打印Log的情况,需要在手机的开发者应用中进行设置。关于打印的格式如果我们不重写的情况下格式是比较乱的,如果想对格式控制一下可以用如下方式

//在HttpLoggingInterceptor的构造方法内传入一个Logger对象,并重写它的log方法
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            //可在该方法中对message进行处理打印
                            Log.e(Tag,message)
                        }
                    });
  1. 第二中方法是可以自定义个拦截器。上代码
    /**
     * 日志拦截器
     */
    private static final Interceptor mLoggingInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();//请求发起的时间
            Log.e("Interceptor", String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();//收到响应的时间
            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            printLog("接受响应", responseBody.string());
            return response;
        }
    };

下面为printlog方法的代码

/**
*   三个参数 Tag就是log中的tag,msg为具体信息
*/
    public static void printLog(String tag, String msg) {
        String message = null;
        try {//需判断json是什么格式
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                message = jsonObject.toString(4);//最重要的方法,就一行,返回格式化的json字符串,其中的数字4是缩进字符数
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(4);
            } else {
                message = msg;
            }
        } catch (JSONException e) {
            message = msg;
        }
        String[] lines = message.split(LINE_SEPARATOR);
        //此处也可以画分割线
         //log.e(tag,"----------------------------------------------")
        for (String line : lines) {
            Log.d(tag, "|" + line);
        }
        //log.e(tag,"----------------------------------------------")
    }

最后记的将自定义的Interceptor 添加到okhttp中,就可实现日志的打印。


以上就是所知的两种方式,如有错误,请多多指正。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,002评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • 有一种师兄叫38℃暖男,我们很少联系,只要联系上肯定是我找他有事。如某年校庆,我给他打电话说,我明天回学校参加校庆...
    大白菜和小乖乖阅读 413评论 0 0
  • 他到我身边一个星期了,每年他到要到我上班的地方呆几个星期,今年他四岁了,有了叛逆行为,而且非常的叛逆,虽已看过大咖...
    知蕊阅读 173评论 0 0
  • 001.思维转换 如果想让我们的生活发生实质性的变化,必须从另外一个角度看问题,即思维转换。 002.原则 如果能...
    丹青医姐阅读 154评论 0 1