这篇文章介绍如何在代码中对 dio 设置代理, 从而实现通过 Charles 等抓包工具来抓包.

Dio 代理设置

在正常情况下, 抓包工具是无法直接抓取 Flutter 应用的网络通信的, 如果需要在开发的时候抓取网络数据, 则可以显式设置 dio http 客户端代理, 代码如下所示:

dart

// 在启用代理的情况下, 且非 production 配置下的代理配置. (其中 usingProxy 是在外部的一个被忽略文件中定义)
if (usingProxy && AppExecutionEnvironment.isDebug) {
  final adapter = _client.httpClientAdapter as DefaultHttpClientAdapter;
  adapter.onHttpClientCreate = (client) {
    // 设置该客户端的代理为指定的 ip:端口
    client.findProxy = (uri) {
      // localProxyIPAddress 和 localProxyPort 是在外部被忽略文件中定义, 方便各个开发者自行更改.
      return 'PROXY $localProxyIPAddress:$localProxyPort';
    };
    // 安卓机上面证书授权:
    client.badCertificateCallback = (cert, host, port) => true;
  };
}

其中 AppExecutionEnvironment 定义如下:

dart
class AppExecutionEnvironment {
  /// 是否是在 debug 配置模式下
  static final bool isDebug = () {
    bool isDebug = false;
    assert(() {
      isDebug = true;
      return true;
    }());
    return isDebug;
  }();

  /// 是否是在 release 配置模式下
  static final bool isRelease = () {
    final isRelease = bool.fromEnvironment("dart.vm.product");
    return isRelease;
  }();

  /// 是否是在 profile 配置模式下
  ///
  /// 实际可能还有其他配置, 都先归入 profile 这里面, 日后再说.
  static final bool isProfile = () {
    final isProfile = !isRelease && !isDebug;
    return isProfile;
  }();

  static void debugDescription() {
    if (isDebug) {
      print('当前在 debug 配置下执行代码');
    } else if (isRelease) {
      print('当前在 release 配置下执行代码');
    } else {
      print('当前在其他配置模式下执行代码');
    }
  }
}

在工程内可以创建一个被 git 忽略的文件, 内容如下:

dart
// HTTP 代理设置 ------------------------------------------------------------

/// 是否启用代理
const usingProxy = false;

/// 代理的 ip 地址
const localProxyIPAddress = '192.168.2.201';

/// 代理端口
const localProxyPort = 9999;

// -------------------------------------------------------------------------