Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

preface

App security is very important, especially data security. However, we know that Charles and other tools can capture the network request of App. If our data is not encrypted, such information will be cleared and extracted and used by criminals. There are many ways to ensure data security. Today we will talk about how to prevent packet capture by taking a few simple steps.

The body of the

When we make a network request, we usually establish a connection through the openConnection of URL, the code is as follows:

URLConnection conn = url.openConnection()
Copy the code

There is also a version of the openConnection function that can pass in a proxy object as follows:

public URLConnection openConnection(Proxy proxy)
    throws java.io.IOException
Copy the code

In this way, when we use this function to establish a connection, we pass a proxy. NO_PROXY to prevent packet capture. Charles and other packet capture tools cannot see our link information, and the code is as follows

URLConnection conn = url.openConnection(Proxy.NO_PROXY)
Copy the code

The official description of proxy. NO_PROXY is as follows:

/**
 * A proxy setting that represents a {@code DIRECT} connection,
 * basically telling the protocol handler not to use any proxying.
 * Used, for instance, to create sockets bypassing any other global
 * proxy settings (like SOCKS):
 * <P>
 * {@codeSocket s = new Socket(Proxy.NO_PROXY); } * * /
public final static Proxy NO_PROXY = new Proxy();

// Creates the proxy that represents a {@code DIRECT} connection.
private Proxy(a) {
    type = Type.DIRECT;
    sa = null;
}
Copy the code

We can see that NO_PROXY is actually a Proxy object whose type is DIRECT. There are three types of NO_PROXY:

  • DIRECT
  • HTTP
  • SOCKS

The official description is as follows:

public enum Type {
    /** * Represents a direct connection, or the absence of a proxy. */
    DIRECT,
    /** * Represents proxy for high level protocols such as HTTP or FTP. */
    HTTP,
    /** * Represents a SOCKS (V4 or V5) proxy. */
    SOCKS
};
Copy the code

So because it is directly connected, so do not go agent. Therefore, Charles and other tools can not catch the package, which ensures data security to a certain extent.

Of course, this method only through the proxy can not capture packets, if the direct route can still capture packets.