使用okhttp和stetho自由地测试网络请求

android网络调试一直是一个比较麻烦的部分,因为在不同序列的请求中,返回的数据会有不同的变化,如果能像web开发一样使用调试功能查看页面的访问数据该是多么美好的事情!
很幸运的是,现在Android开发也可以实时监听网络访问了,能够看到你的发送数据信息,也能够看到返回数据信息。
如图:

使用okhttp和stetho自由地测试网络请求_第1张图片

点击每个请求会看到详细页面,可以查看请求的详情,如图:

使用okhttp和stetho自由地测试网络请求_第2张图片

如果要达到上面的效果,你需要改造你的网络请求模块,使用Chrome浏览器和android程序之间的中间件来连接,这就是本篇要介绍的主题:
OkHttp+Stetho+Chrome进行网络调试。
okhttp是Square的一款非常优秀的网络访问框架,它的使用非常简单,可以通过github去获取其源代码:
https://github.com/square/okhttp
Stetho则是facebook开发的一款连接android程序和Chrome开发者工具的一个桥梁:
https://github.com/facebook/stetho
使用方式:
1.工程依赖包如下:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.facebook.stetho:stetho-okhttp3:1.5.0'
compile 'com.facebook.stetho:stetho:1.5.0'

2.需要继承Application类来初始化Stetho工具。

Stetho.initialize(Stetho
        .newInitializerBuilder(this)
        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
        .enableWebKitInspector(
                Stetho.defaultInspectorModulesProvider(this)).build());

在AndroidManifest.xml需要配置为程序的app:

".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
......
</application>

3.使用okhttp访问的代码如下:

OkHttpClient okHttpclient = new OkHttpClient().newBuilder()
                .addNetworkInterceptor(new StethoInterceptor());

运行程序后就会发现,在chrome中的网址栏输入:chrome://inspect/
可以查看如图:
使用okhttp和stetho自由地测试网络请求_第3张图片

点击蓝色的inspect的连接,既可以看到本文开头的调试画面。

注意:google由于总所周知的原因,不能访问,需要。

文章地址

你可能感兴趣的:(android,test)