retrofit2.0使用拦截器Interceptor统一打印请求与响应的json

开始之前先甩上retrofit和okhttp的github链接:
https://github.com/square/retrofit
https://github.com/square/okhttp

大家都知道一款APP里请求很多,如果能统一打印请求与响应的json自然十分方便。retrofit作为知名网络请求框架,提供了拦截器Interceptor,官方对拦截器的定义:

Interceptors area powerful mechanism that can monitor, rewrite, and retry calls.
拦截器可以用来转换,重试,重写请求的机制。

我们就不转换重写了,只是打印一下就好。

先添加依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
compile 'com.orhanobut:logger:2.1.0' // 打印日志

其实okhttp已经为我们提供了一个Interceptor的实现类:HttpLoggingInterceptor。只要稍作设置就可以:

    HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
    if(BuildConfig.DEBUG){
        //显示日志
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }else {
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
    }
    okHttpClient.addInterceptor(logInterceptor);

这样请求和响应的日志就都会打印出来啦~
但是有些手机比如联想可能会默认屏蔽这样的日志(之前我就是用联想手机测试,还以为这方法不管用),可以在手机上设置使其显示。不同的机器设置方式不一样,搜索一下都有~

如果不想设置或者想自己定义一下打印的格式,可以像下面这样写:

public class LoggingInterceptor implements Interceptor {
  private final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public Response intercept(Chain chain) throws IOException {

    Request request = chain.request();
    RequestBody requestBody = request.body();

    String body = null;

    if(requestBody != null) {
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);

        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        body = buffer.readString(charset);
    }

    Logger.e("发送请求\nmethod:%s\nurl:%s\nheaders: %sbody:%s",
            request.method(), request.url(), request.headers(), body);

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    String rBody = null;

    if(HttpEngine.hasBody(response)) {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                e.printStackTrace();
            }
        }
        rBody = buffer.clone().readString(charset);
    }

    Logger.e("收到响应 %s%s %ss\n请求url:%s\n请求body:%s\n响应body:%s",
            response.code(), response.message(), tookMs, response.request().url(), body, rBody);

    return response;
  }
}

在OkHttpClient中添加拦截:

    OkHttpClient.Builder client = new OkHttpClient.Builder()
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)//设置超时时间
            .retryOnConnectionFailure(true);

    //添加拦截
    if (BuildConfig.DEBUG) {
        client.addInterceptor(new LoggingInterceptor())
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

看一些博客里的文章,好像直接通过下面的代码就可以拦截响应,但是我这么写了并没有看到有日志输出…除非像上面那样重写HttpLoggingInterceptor.Logger的log()方法,难道是其实打印了我没找到?……有知道的小伙伴告知一下
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
———————————————-2017-07-25———————————————-
还真是其实打印了我没找到,见开头。

参考:
Android Retrofit2.0查看log和JSON字符串(HttpLoggingInterceptor)
OkHttp使用(四)拦截器
https://github.com/jaydenxiao2016/AndroidFire
这里还有一篇:
HttpLoggingInterceptor拦截的log信息为unicode字符时的解决办法

    原文作者:哎呦哥哥QAQ
    原文地址: https://www.jianshu.com/p/dfaf8e51f720
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞