首页 > 解决方案 > 如何使用 Swift 5 的代理配置连接到 HTTP 服务器(为什么忽略 connectionProxyDictionary)?

问题描述

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

我尝试使用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。​</p>

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

标签: iosswifthttpproxyswift-playground

解决方案


这些kCFNetworkProxiesHTTP键仅控制用于httpURL 的代理。httpsURL 使用通过kCFNetworkProxiesHTTPS键定义的代理。

不幸的是,HTTPS 密钥在 iOS 上不可用(真的不知道为什么),但实现在那里,所以你可以使用正确的密钥传递字符串,即"HTTPSEnable","HTTPSProxy""HTTPSPort".


推荐阅读