如何使用 Swift 5 的代理配置连接到 HTTP 服务器(为什么忽略 connectionProxyDictionary)?

How to connect to a HTTP server using a proxy configuration with Swift 5 (why connectionProxyDictionary is being ignored)?

我需要连接到 HTTP 代理后面的网络服务器。我试过将 URLSessionConfigurationconnectionProxyDictionary 一起使用,但似乎我的代理配置被忽略了,因为您可以将代理主机值更改为任何值,结果是相同的。

我试过使用Charles Proxy来调试代替我需要连接的代理的情况,发现请求永远不会到达它,所以我相信那里我的客户端代码有问题。

import Foundation

class URLSessionProxy: NSObject, URLSessionDelegate {

    func doRequest() {

        let configuration = URLSessionConfiguration.default
        configuration.connectionProxyDictionary = [
            kCFNetworkProxiesHTTPEnable: true,
            kCFNetworkProxiesHTTPProxy: "localhost",
            kCFNetworkProxiesHTTPPort: "8888",
        ]

        var request = URLRequest(url: URL(string: "https://ip.seeip.org/jsonip")!)
        request.addValue("application/json", forHTTPHeaderField: "Accept")

       URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
        .dataTask(with: request, completionHandler: { (data, response, error) in
            if error == nil {
                print("url request = ", request.url?.absoluteString)
                print("headers request = ", request.allHTTPHeaderFields.debugDescription)
                print("response = ", response)
                print("data body = ", String(data: data!, encoding: String.Encoding.utf8.self))

            } else {
                print("error = ", error)
                print(error?.localizedDescription)
            }
        }).resume()
    }
}

URLSessionProxy().doRequest()

在给出的示例中,我希望使用我在 localhost:8888 上设置的代理间接连接到 ip.seeip.org。

要点:https://gist.github.com/brunabaudel/90a6873d2c3df6caeb89f8b7afc9adce

kCFNetworkProxiesHTTP 键仅控制用于 http URL 的代理。 https 网址使用由 kCFNetworkProxiesHTTPS 键定义的代理。

不幸的是,HTTPS 密钥在 iOS 上不可用(真的不知道为什么),但是实现是存在的,所以您可以传递带有正确密钥的字符串,这些密钥是 "HTTPSEnable" , "HTTPSProxy", 和 "HTTPSPort".