如何在Swift 3中使用URLSession和Proxy [英] How to use URLSession with Proxy in Swift 3

查看:202
本文介绍了如何在Swift 3中使用URLSession和Proxy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于API请求,我正在尝试使用代理设置URLSession。出于测试目的,我使用公共代理和响应IP的API。

For an API Request I'm trying to setup an URLSession using a Proxy. For test purposes I'm using a public Proxy and an API responding the IP.

func makeRequestViaUrlSessionProxy(_ url: String, completion: @escaping (_ result: String?) -> ()) {

    let request = URLRequest(url: URL(string: url)!)

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
    config.connectionProxyDictionary = [AnyHashable: Any]()
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPEnable as String] = 1
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPProxy as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPPort as String] = 8888

    let session = URLSession.init(configuration: config, delegate: nil, delegateQueue: OperationQueue.current)

    let task = session.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            NSLog("Client-side error in request to \(url): \(error)")
            completion(nil)
            return
        }

        if data == nil {
            NSLog("Data from request to \(url) is nil")
            completion(nil)
            return
        }

        let httpResponse = response as? HTTPURLResponse
        if httpResponse?.statusCode != 200 {
            NSLog("Server-side error in request to \(url): \(httpResponse)")
            completion(nil)
            return
        }

        let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
        let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
        let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
        session.invalidateAndCancel()
        completion(stringData)
    }
    task.resume()
}

被叫:

override func viewDidLoad() {
    super.viewDidLoad()
    makeRequestViaUrlSessionProxy("https://api.ipify.org?format=json") { string in
        print(string)
    }
}

好像 config 被完全忽略,因为即使使用组合代理IP,响应的IP也始终是实际设备IP

It seems like the config is completely ignored because even with made up Proxy IP, the responded IP is always the actual devices IP

任何帮助都非常受欢迎。

Any help is highly appreciated.

编辑:根据用户hasan83的建议,HTTPS密钥似乎不是一个选项。

as suggested by User hasan83, taking "the HTTPS keys" seems not an option.


< img src =https://i.stack.imgur.com/SEOkG.pngalt =在此输入图像说明>

推荐答案

我认为工作(应该被弃用)的关键是:

I think the working (supposed to be deprecated) keys are:

kCFStreamPropertyHTTPSProxyHost
kCFStreamPropertyHTTPSProxyPort

你能试试这段代码吗?

func makeRequestViaUrlSessionProxy(_ url: String, completion: @escaping (_ result: String?) -> ()) {

    let request = URLRequest(url: URL(string: url)!)

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
    config.connectionProxyDictionary = [AnyHashable: Any]()
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPEnable as String] = 1
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPProxy as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kCFNetworkProxiesHTTPPort as String] = 8888
    config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyHost as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyPort as String] = 8888

    let session = URLSession.init(configuration: config, delegate: nil, delegateQueue: OperationQueue.current)

    let task = session.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            NSLog("Client-side error in request to \(url): \(error)")
            completion(nil)
            return
        }

        if data == nil {
            NSLog("Data from request to \(url) is nil")
            completion(nil)
            return
        }

        let httpResponse = response as? HTTPURLResponse
        if httpResponse?.statusCode != 200 {
            NSLog("Server-side error in request to \(url): \(httpResponse)")
            completion(nil)
            return
        }

        let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
        let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
        let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
        session.invalidateAndCancel()
        completion(stringData)
    }
    task.resume()
}

另外请确保您的代理服务器配置为处理https请求。

Also please make sure your proxy server is configured to handle https requests.

注意:它可能会为这些键提供已弃用的警告,但键仍然有效(请参阅 https://forums.developer.apple.com/thread/19356#131446

Note: It might give deprecated warning for those keys but keys are still working (see https://forums.developer.apple.com/thread/19356#131446)

这篇关于如何在Swift 3中使用URLSession和Proxy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆