Android OkHttp 網絡請求調試利器 - Monitor

一、概述

Monitor 是我剛開發完成的一個開源項目,適用於使用了 OkHttp 作爲網絡請求框架的項目,可以攔截並緩存應用內的所有 Http 請求和響應信息,且可以以 Notification 和 Activity 的形式來展示具體內容

二、使用

項目主頁:Android OkHttp 網絡請求調試利器 - Monitor

Apk下載:Android OkHttp 網絡請求調試利器 - Monitor

build.gradle 文件中添加依賴:

    implementation 'leavesc.hello:Monitor:1.0.1'

添加 MonitorInterceptor 作爲項目中 OkHttpClient 的攔截器

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new MonitorInterceptor(this)).build();

然後?沒了,OK了

是的,就是這麼簡單,只要添加了 MonitorInterceptor 攔截器,之後 Monitor 就會自動記錄下所有 Http 請求的請求信息以及響應體,且自動彈窗提示。當然,爲了照顧到其他一些特殊情況,Monitor 也對外提供了一些方便訪問的 Api

注意:以下方法需要在實例化 MonitorInterceptor 後再調用,否則會拋出異常

1. 啓動 Http 列表頁

    startActivity(Monitor.getLaunchIntent(MainActivity.this));

2. 開啓彈窗

    Monitor.showNotification(true);

3. 關閉彈窗(當有新數據時也不會顯示)

    Monitor.showNotification(false);

4. 清除彈窗(當有新數據時會再次顯示)

    Monitor.clearNotification();

5. 清除緩存

    Monitor.clearNotification();

6. 監聽 Http 數據變化

        //參數用於監聽最新指定條數的數據變化,如果不傳遞參數則會監聽所有的數據變化
        Monitor.queryAllRecord(10).observe(this, new Observer<List<HttpInformation>>() {
            @Override
            public void onChanged(@Nullable List<HttpInformation> httpInformationList) {
                tv_log.setText(null);
                if (httpInformationList != null) {
                    for (HttpInformation httpInformation : httpInformationList) {
                        tv_log.append(httpInformation.toString());
                        tv_log.append("\n\n");
                        tv_log.append("*************************************");
                        tv_log.append("\n\n");
                    }
                }
            }
        });

三、致謝

Monitor 的一部分靈感來源於另一個開源項目:Chuck,因此你可以看到兩個項目的 UI 基本是相同的,因爲我覺得 UI 是次要的,也懶得去想新的交互方式,我借鑑的主要是其攔截器的數據抓取思路。而因爲我對 Chuck 有些地方不太滿意,包括Notification 無法動態精確控制、無法通過 API 清除緩存、無法監聽數據變化等,所以纔打算自己來實現

此外,Monitor 使用到的依賴還包括:

    implementation "com.squareup.okhttp3:okhttp:3.12.0"
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    implementation 'android.arch.lifecycle:extensions:1.1.1'

當中,okhttp 和 gson 不必說,room 和 lifecycle 都是 Google Jetpack 組件的一部分,room 和 lifecycle 搭配使用真的還是蠻爽的~~

四、結束語

項目主頁:Android OkHttp 網絡請求調試利器 - Monitor

Apk下載:Android OkHttp 網絡請求調試利器 - Monitor

歡迎 star

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章