OkHttp+Stetho+Chrome調試android網路部分(原創)

來源:互聯網
上載者:User

標籤:

android網路調試一直是一個比較麻煩的部分,因為在不同序列的請求中,返回的資料會有不同的變化,如果能像web開發一樣使用調試功能查看頁面的訪問資料該是多麼美好的事情!

很幸運的是,現在Android開發也可以即時監聽網路訪問了,能夠看到你的發送資料資訊,也能夠看到返回資料資訊。 點擊每個請求會看到詳細頁面,可以查看請求的詳情, 如果要達到上面的效果,你需要改造你的網路請求模組,使用Chrome瀏覽器和android程式之間的中介軟體來串連,這就是本篇要介紹的主題:OkHttp+Stetho+Chrome進行網路調試。 okhttp是Square的一款非常優秀的網路訪問架構,它的使用非常簡單,可以通過github去擷取其原始碼:https://github.com/square/okhttp Stetho則是facebook開發的一款串連android程式和Chrome開發人員工具的一個橋樑:https://github.com/facebook/stetho 使用方式:1.工程依賴包如下:commons-cli-1.2.jarokhttp-2.3.0.jarokio-1.3.0.jarstetho-1.0.1.jarstetho-okhttp-1.0.1.jar 2.需要繼承Application類來初始化Stetho工具。
package com.peiandsky.chromedebug;import android.app.Application;import com.facebook.stetho.Stetho;public class App extends Application {    @Override    public void onCreate() {        super.onCreate();        Stetho.initialize(Stetho                .newInitializerBuilder(this)                .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))                .enableWebKitInspector(                        Stetho.defaultInspectorModulesProvider(this)).build());    }}

 

 在AndroidManifest.xml需要配置為程式的app: 3.使用okhttp訪問的代碼如下:
package com.peiandsky.chromedebug;import java.io.IOException;import com.facebook.stetho.okhttp.StethoInterceptor;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;public class Net {    private static final boolean debug = true;    private static OkHttpClient okHttpClient = new OkHttpClient();    static {        if (debug) {            okHttpClient.networkInterceptors().add(new StethoInterceptor());        }    }    public static final void askBaidu() {        Request request = new Request.Builder().url("http://www.baidu.com")                .build();        try {            Response response = okHttpClient.newCall(request).execute();            String reslut = response.body().string();        } catch (IOException e) {            e.printStackTrace();        }    }}

 

 運行程式後就會發現,在chrome中的網址欄輸入: chrome://inspect/ 可以查看 點擊藍色的inspect的串連,既可以看到本文開頭的調試畫面。   

 

OkHttp+Stetho+Chrome調試android網路部分(原創)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.