connectionProxyDictionary 笔记

最近研究了下 connectionProxyDictionary,做一个简单的笔记。官方文档是这么描述的。

This property controls which proxy tasks within sessions based on this configuration use when connecting to remote hosts.
The default value is NULL, which means that tasks use the default system settings.

这个属性可以设置网络代理,默认值是 NULL,使用系统的代理设置。

有一个比较巧妙的用法,可以通过设置为空字典可以禁止代理抓包(charles、fiddler等)。

上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
NSString* proxyHost =  @"192.168.12.23";//@"myProxyHost.com";
NSNumber* proxyPort = [NSNumber numberWithInt: 12345];


// 创建一个代理服务器,包括HTTP或HTTPS代理,当然还可以添加SOCKS,FTP,RTSP等
NSDictionary *proxyDict = @{
(NSString *)kCFNetworkProxiesHTTPEnable : [NSNumber numberWithInt:1],
(NSString *)kCFNetworkProxiesHTTPProxy: proxyHost,
(NSString *)kCFNetworkProxiesHTTPProxyPort: proxyPort,

(NSString *)kCFNetworkProxiesHTTPSEnable : [NSNumber numberWithInt:1],
(NSString *)kCFNetworkProxiesHTTPSProxy: proxyHost,
(NSString *)kCFNetworkProxiesHTTPSProxyPort: proxyPort,
};

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
// 设置代理
configuration.connectionProxyDictionary = proxyDict;

// 禁止代理
configuration.connectionProxyDictionary = @{};

参考资料

1、Apple 文档
2、How to programmatically add a proxy to an NSURLSession