This is the 28th day of my participation in the August Text Challenge.More challenges in August

Access is simple

There are always 1234 steps to simple access, so here are a few simple words.

Gradle configuration

Instead of using MVN and low to download and copy libraries, you can configure gradle directly

/ / Gradle dependency on Stetho dependencies {the compile 'com. Facebook. Stetho: Stetho: 1.3.1'}Copy the code

If you are using the Okhttp 3.x networking stack, please integrate the following networking libraries

Dependencies {the compile 'com. Facebook. Stetho: stetho - okhttp3:1.3.1'}Copy the code

Okhttp 2.2 x +

Dependencies {the compile 'com. Facebook. Stetho: stetho - okhttp: 1.3.1'}Copy the code

If HttpURLConnection is used

Dependencies {the compile 'com. Facebook. Stetho: stetho - urlconnection: 1.3.1'}Copy the code

Please note to the white Rabbit and the Wolf:

  • If you are using Apache HttpClient, sorry, you are out, please upgrade the network stack, of course, you can also learn to understand Stetho’s play after writing a set of network monitoring to Apache HttpClient.
  • If you use a network stack that is not listed above, or if you write network operations in C/C ++, or if you use a protocol other than HTTP/HTTPS, then this part of the network diagnosis and monitoring approach is probably difficult to use. If you want to use it, write it yourself.

Initialize the

There is very little code to write, and almost all applications have the same code, starting with initialization in the Application class

public class MyApplication extends Application { public void onCreate() { super.onCreate(); Stetho.initializeWithDefaults(this); }}Copy the code

This initialization turns on most auscultation modules, except for some additional hook modules such as network monitoring

Network in the diagnosis of

If you are using the network stack OkHttp and the version range is 2.2.x+ to 3.x, all you need to do to open the network diagnostics module is to call the following code at the appropriate place in your application

OkHttp 2.2 x +

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new StethoInterceptor());
Copy the code

OkHttp 3.x

new OkHttpClient.Builder()
    .addNetworkInterceptor(new StethoInterceptor())
    .build();
Copy the code

HttpURLConnection

If you use HttpURLConnection, said a bit troublesome, you can use a Stetho framework SDK provides class StethoURLConnectionManager to diagnose the client network is open, but there are some pits is to pay attention to.

For example, in order for Stetho to report the correct size of the compressed payload to Chrome on the development machine, you need to personally add “accept-Encoding: gzip” to the HTTP/HTTPS request header and process the compressed response data yourself. If you use Okhttp, you don’t have to worry about all this, and the framework takes care of it for you by default.

The reference code is as follows:

private final StethoURLConnectionManager stethoManager;

private static final int READ_TIMEOUT_MS = 10000;
private static final int CONNECT_TIMEOUT_MS = 15000;

private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String GZIP_ENCODING = "gzip";

private String url = "http://www.figotan.org";
stethoManager = new StethoURLConnectionManager(url);

URL url = new URL(url);

// Note that this does not actually create a new connection so it is appropriate to
// defer preConnect until after the HttpURLConnection instance is configured. Do not
// invoke connect, conn.getInputStream, conn.getOutputStream, etc before calling
// preConnect!
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try {
    conn.setReadTimeout(READ_TIMEOUT_MS);
    conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
    conn.setRequestMethod(request.method.toString());

    // Adding this disables transparent gzip compression so that we can intercept
    // the raw stream and display the correct response body size.
    conn.setRequestProperty(HEADER_ACCEPT_ENCODING, GZIP_ENCODING);

    SimpleRequestEntity requestEntity = null;
    if(request.body ! =null) {
        requestEntity = new ByteArrayRequestEntity(request.body);
    }

    stethoManager.preConnect(conn, requestEntity);
    try {
          if (request.method == HttpMethod.POST) {
            if (requestEntity == null) {
              throw new IllegalStateException("POST requires an entity");
            }
            conn.setDoOutput(true);
            requestEntity.writeTo(conn.getOutputStream());
          }

          // Ensure that we are connected after this point. Note that getOutputStream above will
          // also connect and exchange HTTP messages.
          conn.connect();

          stethoManager.postConnect();

    } catch (IOException inner) {
          // This must only be called after preConnect. Failures before that cannot be
          // represented since the request has not yet begun according to Stetho.
          stethoManager.httpExchangeFailed(inner);
          throwinner; }}catch (IOException outer) {
        conn.disconnect();
        throw outer;
}
      
try {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream rawStream = conn.getInputStream();
    try {
        // Let Stetho see the raw, possibly compressed stream.
        rawStream = stethoManager.interpretResponseStream(rawStream);
        if(rawStream ! =null && GZIP_ENCODING.equals(conn.getContentEncoding())) {
            decompressedStream  = new GZIPInputStream(in);
        } else {
            decompressedStream = rawStream;
        } 
    
        if(decompressedStream ! =null) {
            int n;
            byte[] buf = new byte[1024];
            while((n = decompressedStream.read(buf)) ! = -1) {
                out.write(buf, 0, n); }}}finally {
        if(rawStream ! =null) { rawStream.close(); }}}finally {
    conn.disconnect();
}
Copy the code

With the above steps, you can already make your APP support network monitoring, database monitoring, and SharedPreferences file content monitoring. If you want to play more advanced versions, see the custom Dumpapp plugin and Rhino below, and if you want to play directly, read on.