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