catalogue

  • 01. Basic introduction
  • 02. Stetho general process
  • 3. The Android applications
  • 04. How to use it
  • 05. The screenshot of the case is as follows
  • 06. Network request interface information
  • 07. How to use Ping

01. Basic introduction

  • Function of the tool
    • Zhuge Shu network interception analysis mainly analyzes network traffic loss and request, respond process time. Build web analytics tools…
  • See stetho library address
    • Github.com/facebook/st…
  • function
    • Stetho is an open-source Android debugging tool from Facebook.
    • Chrome Developer Tools is a Chrome Developer Tools extension that allows you to check your application’s web, database, WebKit, SharePreference, and more.
    • Developers can also use its Dumpapp tool to provide a powerful command-line interface to access internal applications.

02. Stetho general process

  • The verbal description would look something like this:
    • 1. After the stetho plug-in is installed on the app, a LocalSocketServer (LocalSocketServer) will be started. This local server1 is waiting for the connection of the app(client).
    • At the same time, this local server1 will be connected to another local server2 (ChromeDevtoolsServer).
    • 3. Once the local APP is connected, data will be continuously sent to local server1 and then transferred to Server2.
    • 4. Then Chrome Developer Tools, like a website, visits ChromeDevtoolsServer and presents the data friendly to the Developer, and the process is over.
  • The entire network request is divided into several steps, and the total request time can be subdivided into each step.
    • The DNS. Obtain the IP address of the corresponding domain name from the DNS server. In this step, you need to pay attention to problems such as DNS resolution time, carrier hijacking of LocalDNS, and DNS scheduling.
    • Create a connection. Establish a connection with the server, including TCP three-way handshake, TLS key negotiation and so on. How to choose multiple IP/ ports, whether to use HTTPS, whether to reduce or save the time to create a connection.
    • Send/receive data. After a successful connection is established, you can happily interact with the server to assemble, send, receive, and parse data. Think about how to make good use of bandwidth based on network conditions, how to quickly detect network latency, how to adjust packet size on weak networks, and so on.
    • Close the connection. Closing the connection seems simple enough

3. The Android applications

  • The application code is shown below
    new OkHttpClient.Builder()
        .addNetworkInterceptor(new StethoInterceptor())
        .build()
    Copy the code
  • So since the StethoInterceptor is added to the Web request, it can intercept web request and response information and send it to Chrome. So can you use it yourself…
    • Can the
  • StethoInterceptor Provides an overview of the process
    • The whole process can be simplified as follows: Send a message to Chrome when sending a request, and send a message to Chrome when receiving the request (see NetworkEventReporterImpl implementation for details).
    • Two messages are connected via EventID with types OkHttpInspectorRequest and OkHttpInspectorResponse, Respectively inherited from NetworkEventReporter. InspectorRequest and NetworkEventReporter. InspectorResponse.
    • We simply inherit from these two classes and send a Request and Response to Chrome when our own web library sends and receives requests.
  • How to use it
    • Since Android uses Facebook’s Stetho library, you can block requests from your phone, then go to Chrome and type: Chrome ://inspect in the browser address bar. You can view the request information.
    • How about taking this request information, putting it in a collection, and displaying it on the Android page? This makes it easy to develop and test the network request information, as well as the elapsed time in the request process (such as DNS resolution time, request time, response time, total time, etc.)
  • How to consume recording time
    • There is an EventListener class in the OkHttp library. This class is a listener for network events. Extend this class to monitor the number, size, and duration of HTTP calls to your application.
    • All start/connect/get events will eventually receive a matching end/release event that either succeeds (non-empty arguments) or fails (non-empty throwable).
    • For example, you can log the time at the start of the link; DNS start, end and other methods to resolve the record time, you can calculate the DNS resolution time.
    • For example, you can calculate the connect connection time by recording the time of the start request, connectStart, connectEnd, etc.

04. How to use it

  • As shown below.
    new OkHttpClient.Builder()
        // Configure the factory listener. It is mainly the calculation of network process consumption time
        .eventListenerFactory(NetworkListener.get())
        // Intercepting requests, responses, etc
        .addNetworkInterceptor(new StethoInterceptor())
        .build()
    Copy the code
  • Purpose of the library
    • Make a global hover button, click the button to view the activity page request interface, you can view the request several interfaces, and interface request to response consumption traffic
    • You can view the network request process, such as DNS resolution time, request time, and response time
    • Convenient test view request data, convenient packet capture. You can copy request, respond, body and so on. You can also take screenshots
  • Functions to be improved
    • Add the ping function to detect and diagnose network problems
    • Need to make a hover button, that is, add jump network block list entry
    • After a network request response exceeds 1 second (or possibly 2 seconds), you need to be prompted for that network timeout

05. The screenshot of the case is as follows

06. Network request interface information

  • The request interface is shown below
    • www.wanandroid.com/friend/json
  • General
    • Request URL: www.wanandroid.com/friend/json
    • Request Method: GET
    • Status Code: 200 OK
    • Remote Address: 47.104.74.169:443
    • Referrer Policy: no-referrer-when-downgrade
  • Response Header
    • HTTP / 1.1 200 OK
    • Server: Apache – 1.1 – / – Coyote
    • Cache-Control: private
    • Expires: Thu, 01 Jan 1970 08:00:00 CST
    • Content-Type: application/json; charset=UTF-8
    • Transfer-Encoding: chunked
    • Date: Thu, 10 Sep 2020 01:05:47 GMT
  • Request Header
    • Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/avif, image/webp image/apng,/; Q = 0.8, application/signed – exchange; v=b3; Q = 0.9
    • Accept-Encoding: gzip, deflate, br
    • Accept-Language: zh-CN,zh; Q = 0.9
    • Cache-Control: no-cache
    • Connection: keep-alive
    • Cookie: JSESSIONID=5D6302E64E9734210FA231A6FAF5799E; Hm_lvt_90501e13a75bb5eb3d067166e8d2cad8 = 1598920692159007, 288159094, 016159629, 553; Hm_lpvt_90501e13a75bb5eb3d067166e8d2cad8=1599699419
    • Host: www.wanandroid.com
    • Pragma: no-cache
    • Sec-Fetch-Dest: document
    • Sec-Fetch-Mode: navigate
    • Sec-Fetch-Site: none
    • Upgrade-Insecure-Requests: 1
    • The user-agent: Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36
  • The Response to return to the body
    • Here is omitted
  • See the screenshot below.

07. How to use Ping

  • Screenshot of using ping
  • Ping is a tool
    • Ping is a command on Windows, Unix, and Linux systems. Ping is also a communication protocol and is part of the TCP/IP protocol.
    • You can run the ping command to check whether the network is normal, which helps you analyze and determine network faults.
    • Ping sends an Internet Control Messages Protocol (ICMP) echo request message to the destination and reports whether the desired ICMP Echo was received. Command used to check whether the network is normal or the speed of the connection. In a broad sense, it sends a packet and obtains the network connection status according to the packet loss rate and average time of the returned packet.
  • What does ping do
    • We may encounter the site can not open, when there is not open, we do not know where the problem, do not know whether the resolution of the problem or the site space problems, at this time we can find the problem through ping, see if the site can ping through.
  • Ping on Android
    • In order to check the network, you can also ping android to check whether the network is normal.
    • What are the implementation schemes
      • The disadvantage of simulating the traceroute process by running the ping command in the background thread is that the simulation process is slow and timeout occurs frequently
      • By compiling the code of the open source network detection library iputilsC, ICMP packets sent by the socket are simulated by Traceroute, which can obviously improve the detection speed
        • Deep understanding of iputils web tools: blog.csdn.net/fsdev/categ…
    • Procedure information about code ping
      • Start an AsyncTask and start parsing in the doInBackground method, which is the entry point.
      • Add header information, including: Start diagnosis + output basic information about application, machine, and network diagnosis + Output local network environment information
      • TCP Three-way handshake
        • To start executing the link, there are two important pieces of information. One is the IP set, the other is the InetAddress array, iterates [length is IP set length], and then executes the request
        • Create a socketAddress with two parameters, IP and port number 80. Then the for loop executes the socket request
        • During socket request execution, if a timeout SocketTimeoutException is detected, the data is logged
        • When timeOut occurs, extend the connection time. Note that the connection times out for two consecutive times and stop the subsequent test. If I/O exceptions occur for two consecutive times, stop the subsequent test
        • Of course, as long as there is a complete successful process, then three successful handshake operations will be recorded
      • Diagnose ping information and synchronize the process. This is mainly to monitor the network directly through the ping command
        • Create a NetPing object and set the number of packets to be sent at each ping to four
        • Then ping the local IP address, the local IP address, and the local DNS. What is the ping instruction? This is mostly about executing instructions using Runtime in Java…
      • Start diagnosing traceRoute
        • The native JNI code is called first and the JNI C function is called to perform the traceroute procedure. If an exception occurs, Java code is called to perform the operation…
        • Then run the ping command to simulate the traceroute process, for example, ping -c 1 -t 1 www.jianshu.com
        • If trace:IP is successfully obtained, the ping command is sent again to obtain the ping time
  • How is ping used in this project
    • Create a ping directly, passing in a url
      _netDiagnoService = new NetDiagnoService(getContext(), getContext().getPackageName()
              , versionName, userId, deviceId, host, this);
      _netDiagnoService.execute();
      Copy the code
    • How to cancel ping
      if(_netDiagnoService! =null){
          _netDiagnoService.cancel(true);
          _netDiagnoService = null;
      }
      Copy the code
    • Or stop ping. Stop thread permission and set the object to NULL
      _netDiagnoService.stopNetDialogsis();
      Copy the code
    • About listening
      /** * All logs are output@paramLog Log output */
      @Override
      public void OnNetDiagnoFinished(String log) {
          setText(log);
      }
      
      /** * Monitor log output during network diagnosis *@paramLog Log output */
      @Override
      public void OnNetDiagnoUpdated(String log) {
          showInfo += log;
          setText(showInfo);
      }
      Copy the code

Library address:Github.com/yangchong21…