项目中一直在用SocketRocket库做WebSocket的网络通信的基础库,但是其一直不支持代理抓包(最新版0.6.0已经支持,但由于为SDK项目,依赖的三方库也不能轻易升级,所以代理功能的实现依然要在0.5.1的基础上,最小限度得修改代码),经过研究和对比发现,仅需添加几行代码,即可使其通信内容被Charles代理成功抓包,改动如下:
- (void)_initializeStreams;
{
assert(_url.port.unsignedIntValue <= UINT32_MAX);
uint32_t port = _url.port.unsignedIntValue;
if (port == 0) {
if (!_secure) {
port = 80;
} else {
port = 443;
}
}
NSString *host = _url.host;
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
//在debug时,添加如下代码即可支持代理抓包
#if DEBUG
CFDictionaryRef proxyDict = CFNetworkCopySystemProxySettings();
CFMutableDictionaryRef socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict);
NSDictionary *dict = CFBridgingRelease(socksConfig);
NSString *ip = [dict objectForKey:@"HTTPSProxy"];
if (ip.length > 0) {
NSDictionary *proxySocksConfig = @{@"SOCKSProxy": ip, @"SOCKSPort": @(8889), @"SOCKSEnable": @(true)};
CFDictionaryRef config = CFBridgingRetain(proxySocksConfig);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertySOCKSProxy, config);
CFReadStreamSetProperty(readStream, kCFStreamPropertySOCKSProxy, config);
CFRelease(config);
}
CFRelease(proxyDict);
#endif
_outputStream = CFBridgingRelease(writeStream);
_inputStream = CFBridgingRelease(readStream);
_inputStream.delegate = self;
_outputStream.delegate = self;
}
仅供有需要的朋友在Debug环境下开启抓包的能力
参考文章:https://stackoverflow.com/questions/33090087/how-to-inspect-websocket-traffic-with-charlesproxy-for-ios-simulator-devices