使用facebook的Stetho监控app的网络访问

接之前用Stetho调试数据库的文章, 默认chrome://inspect/#devices中的network是空白页.
如果要监测网络访问, 需要额外再做一些工作.
如果项目中直接使用HttpURLConnection实现网络访问的话, 需要配合使用StethoURLConnectionManager来完成对网络的监控, 但我没找到如何使用这个类, 也就不再细究它了.
Stetho和okhttp都是facebook出品的, 因此它俩肯定能配合的很好.

下面记录下如何使用okhttp, 并且让Stetho能够成功的检测到网络数据.

  1. 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'
}
  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();
    }
}

  1. 调用API访问url.
OkHttpUtil.getInstance().requestData(requestUrl);
  1. 打开 chrome://inspect/#devices
    这时, 网络数据的传输就可以被成功的监测到了.

---DONE.------

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容