美文网首页Android Other
Retrofit2.0+okhttp3.0 添加日志拦截器 In

Retrofit2.0+okhttp3.0 添加日志拦截器 In

作者: Mr_不靠谱_先森 | 来源:发表于2017-04-01 15:40 被阅读777次

    retrofit 基于okhttp。使用retrofit /okhttp时候,这些都会wifi
    直连的,不走系统的wifi设置,代理是抓不到包的。所以如果
    想抓包那么抓网卡吧,打印请求或者添加公共参数或者签名之类的话,可以使用拦截器来添加。

    拦截器这里使用okhttp的应用拦截器,分别对get post添加统一参数和签名
    首先实现 interceptor创建自己的拦截器

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addNetworkInterceptor(new LoggingInterceptor());
    
      private static class LoggingInterceptor implements Interceptor {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                //这个chain里面包含了request和response,所以你要什么都可以从这里拿
                Request request = chain.request();
    
                long t1 = System.nanoTime();//请求发起的时间
                DebugLog.i(String.format(Locale.CHINA, "发送请求 %s on %s%n%s",
                        request.url(), chain.connection(), request.headers()));
    
                Response response = chain.proceed(request);
    
                long t2 = System.nanoTime();//收到响应的时间
    
                ResponseBody responseBody = response.peekBody(1024 * 1024);
    
                //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一 
            //个新的response给应用层处理
                DebugLog.i(String.format(Locale.CHINA, "接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                        response.request().url(),
                        responseBody.string(),
                        (t2 - t1) / 1e6d,
                        response.headers()));
    
                return response;
            }
        }
    

    相关文章

      网友评论

        本文标题:Retrofit2.0+okhttp3.0 添加日志拦截器 In

        本文链接:https://www.haomeiwen.com/subject/anbiottx.html