如何以编程方式将代理添加到NSURLSession [英] How to programmatically add a proxy to an NSURLSession
本文介绍了如何以编程方式将代理添加到NSURLSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看 NSURLSession
和 NSURLSessionConfiguration
的文档,我的印象是我应该用字典配置它如下所示:
Looking over the documentation of NSURLSession
and NSURLSessionConfiguration
, I was under the impression I should configure it with a dictionary like the following:
// Create a dictionary to describe the proxy
NSDictionary *proxyDict = @{
(NSString *)kCFProxyHostNameKey : @"myProxyHost.com",
(NSString *)kCFProxyPortNumberKey : @"12345",
(NSString *)kCFProxyTypeKey : (NSString*)kCFProxyTypeHTTP
};
// Create a configuration that uses the dictionary
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setConnectionProxyDictionary:proxyDict];
然而,来自 NSURLSession
的请求是用这个配置直接连接。
However, the requests from NSURLSession
created with this configuration connect directly.
推荐答案
事实证明,你想要的字典键是Stream变体,它们是解析的下到HTTPProxy等:
It turns out, the dictionary keys you want are the Stream variants, they are the ones that resolve down to "HTTPProxy" and such:
NSString* proxyHost = @"myProxyHost.com";
NSNumber* proxyPort = [NSNumber numberWithInt: 12345];
// Create an NSURLSessionConfiguration that uses the proxy
NSDictionary *proxyDict = @{
@"HTTPEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFStreamPropertyHTTPProxyHost : proxyHost,
(NSString *)kCFStreamPropertyHTTPProxyPort : proxyPort,
@"HTTPSEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFStreamPropertyHTTPSProxyHost : proxyHost,
(NSString *)kCFStreamPropertyHTTPSProxyPort : proxyPort,
};
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
// Create a NSURLSession with our proxy aware configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// Form the request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com?2"]];
// Dispatch the request on our custom configured session
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"NSURLSession got the response [%@]", response);
NSLog(@"NSURLSession got the data [%@]", data);
}];
NSLog(@"Lets fire up the task!");
[task resume];
这篇关于如何以编程方式将代理添加到NSURLSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文