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

时间:2015-01-23 01:20:14

标签: ios proxy nsurlsession nsurlsessionconfiguration

查看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请求会直接连接。

6 个答案:

答案 0 :(得分:18)

事实证明,你想要的字典键是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];

答案 1 :(得分:8)

如果有人需要这个版本的快速版本:

Swift 3

let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable as AnyHashable: true,
    kCFNetworkProxiesHTTPPort as AnyHashable: 999, //myPortInt
    kCFNetworkProxiesHTTPProxy as AnyHashable: "myProxyUrlString"
]
let session = URLSession(configuration: sessionConfiguration)

答案 2 :(得分:7)

由于Jeff的几个回答键已被弃用,我使用了这些

NSMutableDictionary *proxy=[NSMutableDictionary dictionaryWithDictionary:@{(__bridge NSString *)kCFNetworkProxiesHTTPEnable  : @1,  (__bridge NSString *)kCFNetworkProxiesHTTPSEnable : @1}];
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPProxy] =host;
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPSProxy]=host;
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPPort]  =port;
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPSPort] =port;
proxy[(__bridge NSString *)kCFProxyUsernameKey]=user;
proxy[(__bridge NSString *)kCFProxyPasswordKey]=password;

configuration.connectionProxyDictionary=proxy;

答案 3 :(得分:4)

kCFProxyPortNumberKey值应为Int而不是String

答案 4 :(得分:2)

Swift 3扩展程序

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
float *test(){
  float *buff = malloc(3* sizeof(float));
  int i, j;
  for (i = 0; i < 3; ++i) {
    buff[i] = (float) (6.31 + i);
  }
  free(buff);
  int n = 10;
  for(i=0;i<n;i++)
  {
    printf("Iteration %d ", i);
    for (j = 0; j < 3; ++j) {
      printf("%f, ", buff[i]);
    }    
    printf("\n");
    buff = malloc(3 * sizeof(float));
    free(buff);
  }
  return buff;

}
int main(){
  int i;
  float *ssd;
  ssd = test();
  printf("\n \n");
  memset(ssd, 0.0, 3*sizeof(float));
  for (i = 0; i < 3; ++i) {
    printf("%f, ", ssd[i]);
  }
  printf("\n \n");
}

用法:

extension URLSession {

    func withProxy(proxyURL: String, proxyPort: Int) -> URLSession {

        var configuration = self.configuration

        configuration.connectionProxyDictionary = [
            kCFNetworkProxiesHTTPEnable as AnyHashable : true,
            kCFNetworkProxiesHTTPPort as AnyHashable : proxyPort,
            kCFNetworkProxiesHTTPProxy as AnyHashable : proxyURL
        ]

        return URLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.delegateQueue)
    }
}

答案 5 :(得分:2)

根据之前的所有回复,这适用于Swift 4,HTTP和HTTPS:

let proxyHost = "127.0.0.1"
let proxyPort = 8888
let configuration = URLSessionConfiguration.default
configuration.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable: true,
    kCFNetworkProxiesHTTPProxy: proxyHost,
    kCFNetworkProxiesHTTPPort: proxyPort,
    kCFNetworkProxiesHTTPSEnable: true,
    kCFNetworkProxiesHTTPSProxy: proxyHost,
    kCFNetworkProxiesHTTPSPort: proxyPort
]

proxyHost应该是主机名,不包含任何URL方案。