zoukankan      html  css  js  c++  java
  • OkHttp+Stetho+Chrome调试android网络部分(原创)

    android网络调试一直是一个比较麻烦的部分,因为在不同序列的请求中,返回的数据会有不同的变化,如果能像web开发一样使用调试功能查看页面的访问数据该是多么美好的事情!

    很幸运的是,现在Android开发也可以实时监听网络访问了,能够看到你的发送数据信息,也能够看到返回数据信息。
    如图:
     
    点击每个请求会看到详细页面,可以查看请求的详情,如图:
     
    如果要达到上面的效果,你需要改造你的网络请求模块,使用Chrome浏览器和android程序之间的中间件来连接,这就是本篇要介绍的主题:
    OkHttp+Stetho+Chrome进行网络调试。
     
    okhttp是Square的一款非常优秀的网络访问框架,它的使用非常简单,可以通过github去获取其源代码:
     
    Stetho则是facebook开发的一款连接android程序和Chrome开发者工具的一个桥梁:
     
    使用方式:
    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的连接,既可以看到本文开头的调试画面。
     
     
     
  • 相关阅读:
    Liferay安装maven
    html之pre标签
    a标签使用注意事项
    AngularJS学习记录
    页面不能访问,抛出 spring java.lang.IllegalArgumentException: Name for argument type [java.lang.String] 异常
    ant编译的时候,报错文件不存在,以及版本不一致
    Eclipse 更改Java 版本的方法
    总结一下本次准备环境时遇到的问题,以供下次参考
    数据上下文中的AddOrUpdate方法
    推荐一款github管理神器SourceTree
  • 原文地址:https://www.cnblogs.com/peiandsky/p/4394779.html
Copyright © 2011-2022 走看看