web-dev-qa-db-ja.com

NSURLSessionにプログラムでプロキシを追加する方法

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からのリクエストは直接接続します。

12
Jeff

必要な辞書キーは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];
20
Jeff

誰かがこれの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)
8
Travis M.

ジェフの回答キーのいくつかは廃止されたので、私はこれを使用します

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

kCFProxyPortNumberKeyの値はIntではなくStringである必要があります

4
Oleg Kovtun

Swift 3拡張機能

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)
    }
}

使用法:

let session = URLSession().withProxy(proxyURL: "xxxxxx", proxyPort: 8321)
2
Med Abida