gpt4 book ai didi

ios - 如何以编程方式将代理添加到 NSURLSession

转载 作者:技术小花猫 更新时间:2023-10-29 10:29:41 26 4
gpt4 key购买 nike

查看 NSURLSessionNSURLSessionConfiguration 的文档,我的印象是我应该用如下字典配置它:

    // 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 的请求直接连接。

最佳答案

事实证明,您想要的字典键是 Stream 变体,它们是解析为“HTTPProxy”的那些:

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];

关于ios - 如何以编程方式将代理添加到 NSURLSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com