retrofit2.0使用攔截器Interceptor統(tǒng)一打印請(qǐng)求與響應(yīng)的json

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

大家都知道一款A(yù)PP里請(qǐng)求很多,如果能統(tǒng)一打印請(qǐng)求與響應(yīng)的json自然十分方便。retrofit作為知名網(wǎng)絡(luò)請(qǐng)求框架,提供了攔截器Interceptor,官方對(duì)攔截器的定義:

Interceptors area powerful mechanism that can monitor, rewrite, and retry calls.
攔截器可以用來轉(zhuǎn)換,重試,重寫請(qǐng)求的機(jī)制。

我們就不轉(zhuǎn)換重寫了,只是打印一下就好。


先添加依賴:

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' // 打印日志

其實(shí)okhttp已經(jīng)為我們提供了一個(gè)Interceptor的實(shí)現(xiàn)類:HttpLoggingInterceptor。只要稍作設(shè)置就可以:

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

這樣請(qǐng)求和響應(yīng)的日志就都會(huì)打印出來啦~
但是有些手機(jī)比如聯(lián)想可能會(huì)默認(rèn)屏蔽這樣的日志(之前我就是用聯(lián)想手機(jī)測試,還以為這方法不管用),可以在手機(jī)上設(shè)置使其顯示。不同的機(jī)器設(shè)置方式不一樣,搜索一下都有~

如果不想設(shè)置或者想自己定義一下打印的格式,可以像下面這樣寫:

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("發(fā)送請(qǐng)求\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("收到響應(yīng) %s%s %ss\n請(qǐng)求url:%s\n請(qǐng)求body:%s\n響應(yīng)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)//設(shè)置超時(shí)時(shí)間
            .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();

看一些博客里的文章,好像直接通過下面的代碼就可以攔截響應(yīng),但是我這么寫了并沒有看到有日志輸出...除非像上面那樣重寫HttpLoggingInterceptor.Logger的log()方法,難道是其實(shí)打印了我沒找到?......有知道的小伙伴告知一下
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
----------------------------------------------2017-07-25----------------------------------------------
還真是其實(shí)打印了我沒找到,見開頭。

參考:
Android Retrofit2.0查看log和JSON字符串(HttpLoggingInterceptor)
OkHttp使用(四)攔截器
https://github.com/jaydenxiao2016/AndroidFire
這里還有一篇:
HttpLoggingInterceptor攔截的log信息為unicode字符時(shí)的解決辦法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容