接之前用Stetho调试数据库的文章, 默认chrome://inspect/#devices中的network是空白页.
如果要监测网络访问, 需要额外再做一些工作.
如果项目中直接使用HttpURLConnection实现网络访问的话, 需要配合使用StethoURLConnectionManager来完成对网络的监控, 但我没找到如何使用这个类, 也就不再细究它了.
Stetho和okhttp都是facebook出品的, 因此它俩肯定能配合的很好.
下面记录下如何使用okhttp, 并且让Stetho能够成功的检测到网络数据.
- build.gradle.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
...
compile 'com.facebook.stetho:stetho:1.3.1'
compile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
}
- 写一个OkHttpUtil.java
package com.hola.weather.utils;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by wangxin on 17-8-4.
*/
public class OkHttpUtil {
private static OkHttpClient mOkHttpClient;
private static OkHttpUtil mInstance;
private OkHttpUtil() {
mOkHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
}
public static OkHttpUtil getInstance() {
if(mInstance == null) {
mInstance = new OkHttpUtil();
return mInstance;
}
return mInstance;
}
public static String requestData(String address) throws Exception {
Request request = new Request.Builder()
.url(address)
.build();
Response response = mOkHttpClient.newCall(request).execute();
return response.body().string();
}
}
- 调用API访问url.
OkHttpUtil.getInstance().requestData(requestUrl);
- 打开 chrome://inspect/#devices
这时, 网络数据的传输就可以被成功的监测到了.
---DONE.------
网友评论