平台、工具
macOS、Charles
步骤
-
下载 Charles 证书
image.png - 手机上安装
命令行使用 adb push 命令将 PC 端下载的 CA 证书推送到手机上的 Download 目录:
adb push ~/Downloads/charles-ssl-proxying-certificate.pem sdcard/Download
安装:设置-安全-加密与凭证-安装证书- CA 证书,选择 Download 文件夹中的证书安装
安装成功后可以在:设置-安全-加密与凭证-信任的凭证-用户,下看到 Charles CA 证书 - 代码实现 Proxy 配置
实现方案是 Flutter 端通过 MethodChannel 获取 Android 端的 Proxy host 以及 port(这部分借鉴了https://juejin.cn/post/7029974646137028638),也可以用 pigeon 工具简化了 channel 的配置,代码如下:
flutter 端获取 proxy
MethodChannel channel =
const MethodChannel('flutter_channel_get_proxy_config');
Future<String> getHost = channel.invokeMethod('getProxyHost');
Future<String> getPort = channel.invokeMethod('getProxyPort');
var result = await Future.wait([getHost, getPort]);
if (result?.length == 2 &&
(result[0]?.isNotEmpty ?? false) &&
(result[1]?.isNotEmpty ?? false)) {
String host = result[0].toString();
String port = result[1].toString();
// 将该句中 _dio 替换为项目中 dio 实例
(_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
// 设置代理
client.findProxy = (uri) {
return "PROXY $host:$port";
};
// 信任证书,否则会请求失败
client.badCertificateCallback = (cert, host, port) {
return true;
};
return client;
};
}
Android 端提供 proxy 配置
class HttpProxyPlugin(messenger: BinaryMessenger): MethodChannel.MethodCallHandler {
private var channel: MethodChannel? = null
init {
channel = MethodChannel(messenger, "flutter_channel_get_proxy")
channel?.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"getProxyHost" -> result.success(getProxyHost())
"getProxyPort" -> result.success(getProxyPort())
}
}
private fun getProxyHost(): String? {
return System.getProperty("http.proxyHost")
}
private fun getProxyPort(): String? {
return System.getProperty("http.proxyPort")
}
}
- 以上配置完成后,在手机上按照正常 Charles 抓包设置好就可以抓 https 的包了
网友评论