天天看點

使用Stetho調試Retrofit的網絡請求使用Stetho調試Retrofit的網絡請求

使用Stetho調試Retrofit的網絡請求

Stetho是Facebook出品的一個非常強大的Android調試工具。在基于你已經正常使用Retrofit或者okhttp的情況下,隻需要簡單3步,你就可以在Chrome上的Developer Tools中調試你Retrofit的請求了。就像Web開發使用調試功能檢視頁面的通路資料一樣那麼友善。不僅如此,你還可以在裡面直接檢視SQLite中的資料等等等。。。步驟如下:

  • Step1:添加依賴
compile 'com.facebook.stetho:stetho:1.3.1'
compile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
           
  • Step2:初始化Stetho
public class MyApplication extends Application {
  public void onCreate() {
    super.onCreate();
    if (BuildConfig.DEBUG) {
        Stetho.initializeWithDefaults(this);
    }
  }
}
           

(一般放在Application中,注意僅需在Debug模式下打開,否則會對CPU跟記憶體都有很大的影響。不信?打開Android Studio的Monitors,你會看見記憶體在不斷的上漲然後GC,如此反複-_-|||。應該是在底層維護了一個socket的長連接配接之類的吧。)

  • Step3:在初始化

    OkHttpClient

    的時候添加

    Interceptor

    ,最後在

    Retrofit

    中設定為預設的client。
Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
// Enable stetho interceptor just in debug mode
if (BuildConfig.DEBUG) {
    OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(new StethoInterceptor())
            .build();
    builder.client(client);
}
           

完成上述的步驟之後,重新run一下你的應用程式。在Chrome的位址欄輸入

chrome://inspect

檢視device狀态,應該可以看見你應用的程序出現在了此處,點選inspect按鈕即可進入調試界面。注意,如果第一次打開很久進不去,需要肉身翻牆-_-|||。。。如下圖:

使用Stetho調試Retrofit的網絡請求使用Stetho調試Retrofit的網絡請求

然後在App中進行相應的網絡請求,在Network這一欄中即可看見剛剛發出的網絡請求,Request和Response的資料都可以友善的檢視,簡直是接口調試神器有木有~

使用Stetho調試Retrofit的網絡請求使用Stetho調試Retrofit的網絡請求
使用Stetho調試Retrofit的網絡請求使用Stetho調試Retrofit的網絡請求

最後順便吐槽下,有兩個比較坑爹的點:

1.如果你的請求與檔案相關,切換到到Preview或者Response的時候回卡UI,他會把檔案資料以字元串的形式顯示,然後就一直在卡着UI,檔案資料越大,卡得越久。是以調試的時候我都把上傳的圖檔改得小小的。Github上有人報issue了,有興趣可以關注這裡issues329,很遺憾它還是open的。

2.每次關閉程序,都會Connection Lose,是以你不得不再次Inspect,這點挺惡心的,就不能自動重新連接配接麼。-_-|||