使用 Proxyman 拦截并调试 iOS 模拟器和真机上的 WebSocket
如果你的 iOS 应用使用 URLSessionWebSocketTask,或 Starscream、SocketRocket 等 iOS WebSocket 库,Proxyman 默认可能无法抓取 WS/WSS 流量。
原因
这是 Apple 有意为之的设计。URLSessionWebSocketTask 不遵循系统的 HTTP 代理设置,所有 WS/WSS 流量都会直接发往互联网,因此 Proxyman 或 Charles Proxy 都无法抓取它们。
本文内容
- 在开发阶段,我们将使用 Proxyman 抓取 iOS 设备(iOS 18 或更高版本)上的 WebSocket 消息。
解决方案
本教程将介绍如何在开发阶段,借助功能强大的 HTTP/HTTPS 和 WebSocket 调试工具 Proxyman,拦截并调试 iOS 设备上的 WebSocket 消息。
本教程的步骤如下:
- 准备 Proxyman
- 在 iOS 设备(iPhone / iPad)或 iOS 模拟器上配置 Proxyman
- 启动 Proxyman SOCKS Proxy Server
- 配置应用使用 Proxyman SOCKS Proxy Server
- 搞定!Proxyman 将抓取你的应用发出的 WebSocket 消息,支持 URLSessionWebSocketTask。
如需查看代码,请访问 GitHub。
1. 准备 Proxyman
首先,获取 Proxyman 最简单的方式是从 Proxyman 官网 直接下载,或者通过终端下载。
$ brew cask install proxyman
2. 在 iOS 模拟器或 iOS 设备上配置 Proxyman
2.1 iOS 模拟器
- 依次进入
Certificate Menu->Install for iOS->iOS Simulators - 按照提示完成所有步骤,将证书安装到 iOS 模拟器中。(请确保至少有一个 iOS 模拟器)
- 完成。

2.2 iOS 设备
Certificate Menu->Install for iOS->iOS Devices- 按照提示完成所有步骤,将证书安装到你的 iOS 设备中。
- 请务必完成最后一步,在 iOS 设备上信任 Proxyman 证书。
- 完成。

3. 启动 Proxyman SOCKS Proxy Server
- 打开 Proxyman 应用 ->
Tools->Proxy Settings->SOCKS Proxy settings->Enable - 记下端口号。此时默认端口为
8889。 - 完成。

4. 配置应用使用 Proxyman SOCKS Proxy Server
请根据你使用的 WebSocket 库,参考以下说明进行操作:
4.1 使用 NWConnection
let parameters = webSocketURL.scheme == "wss" ? NWParameters.tls : NWParameters.tcp
let options = NWProtocolWebSocket.Options()
options.autoReplyPing = true
parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0)
if #available(iOS 17.0, *) {
let socksv5Proxy = NWEndpoint.hostPort(host: "x.x.x.x", port: 8889) // Replace with your Proxyman SOCKS Proxy Server IP address
let config = ProxyConfiguration.init(socksv5Proxy: socksv5Proxy)
let context = NWParameters.PrivacyContext(description: "my socksv5Proxy")
context.proxyConfigurations = [config]
parameters.setPrivacyContext(context)
}
let connection = NWConnection(to: .url(webSocketURL), using: parameters)
connection.start(queue: .main)
4.2 使用 URLSession 和 URLSessionWebSocketTask
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.default
if #available(iOS 17.0, *) {
let socksv5Proxy = NWEndpoint.hostPort(host: "x.x.x.x", port: 8889) // Replace with your Proxyman SOCKS Proxy Server IP address
let proxyConfig = ProxyConfiguration.init(socksv5Proxy: socksv5Proxy)
config.proxyConfigurations = [proxyConfig]
}
return URLSession(configuration: config, delegate: nil, delegateQueue: nil)
}()
5. 完成
搞定!Proxyman 将抓取你的应用发出的 WebSocket 消息 🎉

6. 替代方案
如果你不想修改应用代码,可以使用 Atlantis 框架来抓取 WebSocket 消息。
接下来做什么?
你可以在 Proxyman 的官方文档中进一步了解 WebSocket。
请仅在调试版本中保留 SOCKS 设置,正式发布的应用不应依赖你的开发代理。通过 Proxyman Automatic Setup 会话启动的网页浏览器和服务器,通常无需添加这段 iOS 代码即可被抓取。当你提供消息结构信息时,Proxyman 还能解码 WebSocket 的 Protobuf 负载,这比手动阅读二进制帧轻松得多。
Proxyman 是一款高性能的 macOS 应用,可帮助开发者抓取并检查来自 iOS 设备、iOS 模拟器和 Android 设备上应用及域名的 HTTP/HTTPS 请求。
下载地址:https://proxyman.com
