Flutter 跨端网络抓包 (以Android 为例)

背景

在很多公司测试环境使用的是内网测试,我们公司也是。

但是我们有点扯的是内网的域名没有配置内网域名解析,必须手动配置hosts才可以正常访问测试环境的域名。
如下:

# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost

# 公司内部域名
10.11.x.x   http://www.xxxx.com

所以在测试环境时,操作步骤一般是:在电脑上配置hosts后,然后手机链接电脑上的代理,在进行测试。

在我们之前没有使用Flutter技术的时候,手机链接电脑上的代理,啥问题都没有。电脑上装一个charles

然后在手机上链接电脑的IP

但是我们使用了Flutter技术后,发现这一套不好使了,下面进入今天的主题,分析一下这样做为什么抓不到包的原因以及解决方法。

原因分析

我们知道要科学上网访问国外的一些资源需要设置代理服务器,那么下面 以Android的Java为例,讲解代理.

Java代理

Java 中代理主要的两个类Proxy和ProxySelector,先看一下 Proxy

public class Proxy {
   

    /**
     * Represents the proxy type.
     *
     * @since 1.5
     */
    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
    };

    private Type type;
    private SocketAddress sa;

    /**
     * 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;
    }
    ......

看代码我们可以知道,代理一般分为DIRECT(也被称为没有代理 NO_PROXY),HTTP代理(高级协议代理,HTTP、FTP等的代理),SOCKS 代理.

这个类怎么用呢?以获取百度网页为例,设置URLConnection的代理

    private final String PROXY_ADDR = "xxx.xxx.xxx.xxx";
    private final int PROXY_PORT = 10086;

    public void readHtml() throws IOException {
   
        URL url = new URL("http://www.baidu.com"); 
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_ADDR, PROXY_PORT));
        //链接时,使用代理链接
        URLConnection conn = url.openConnection(proxy); 
        conn.setConnectTimeout(3000);

        InputStream inputStream = conn.getInputStream()
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值