当我们进行网络请求的时候,一般通过URL的openConnection来建立连接
URLConnection conn = url.openConnection()
openConnection还有一个版本,可以传入proxy
public URLConnection openConnection(Proxy proxy)
throws java.io.IOException
我们通过这个函数,传入一个Proxy.NO_PROXY即可防止Charles等工具抓包,如下
URLConnection conn = url.openConnection(Proxy.NO_PROXY)
Proxy.NO_PROXY描述如下:
/**
* 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>
* {@code Socket 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() {
type = Type.DIRECT;
sa = null;
}
可以看到NO_PROXY实际上就是type为DIRECT的一个proxy,这个type有三种:
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
};
这样因为是直连,所以不走代理。所以Charles抓不到包。
当然这种方式只是通过代理抓不到包,如果直接通过路由还是可以抓包的。