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

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.工程依赖包如下:

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:

<application
        android:name=".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/
可以查看如图:
这里写图片描述

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

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

翻墙文章地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值