您的位置:首页 > 理论基础 > 计算机网络

OkHttp+Stetho+Chrome调试android网络部分

2016-04-02 21:42 621 查看

OkHttp+Stetho+Chrome调试android网络部分

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.jar
okhttp-2.3.0.jar
okio-1.3.0.jar
stetho-1.0.1.jar
stetho-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的连接,既可以看到本文开头的调试画面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: