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

von4xj4u  于 2022-10-04  发布在  Swift
关注(0)|答案(2)|浏览(225)

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

我尝试使用Charles Proxy来调试情况,而不是我需要连接的Proxy,发现请求从未到达,所以我认为我的客户端代码有问题。

  1. import Foundation
  2. class URLSessionProxy: NSObject, URLSessionDelegate {
  3. func doRequest() {
  4. let configuration = URLSessionConfiguration.default
  5. configuration.connectionProxyDictionary = [
  6. kCFNetworkProxiesHTTPEnable: true,
  7. kCFNetworkProxiesHTTPProxy: "localhost",
  8. kCFNetworkProxiesHTTPPort: "8888",
  9. ]
  10. var request = URLRequest(url: URL(string: "https://ip.seeip.org/jsonip")!)
  11. request.addValue("application/json", forHTTPHeaderField: "Accept")
  12. URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
  13. .dataTask(with: request, completionHandler: { (data, response, error) in
  14. if error == nil {
  15. print("url request = ", request.url?.absoluteString)
  16. print("headers request = ", request.allHTTPHeaderFields.debugDescription)
  17. print("response = ", response)
  18. print("data body = ", String(data: data!, encoding: String.Encoding.utf8.self))
  19. } else {
  20. print("error = ", error)
  21. print(error?.localizedDescription)
  22. }
  23. }).resume()
  24. }
  25. }
  26. URLSessionProxy().doRequest()

在给定的示例中,我希望使用我在本地主机上设置的代理间接连接到ip.seeip.org:8888.​

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

6yjfywim

6yjfywim1#

kCFNetworkProxiesHTTP键仅控制用于http URL的代理。https URL使用使用kCFNetworkProxiesHTTPS密钥定义的代理。

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

ecfsfe2w

ecfsfe2w2#

非常感谢。以下代码可以正常工作:

  1. let configuration = URLSessionConfiguration.default
  2. let proxyConfiguration: [AnyHashable : Any] = [
  3. "HTTPSEnable": 1,
  4. "HTTPSProxy": "host.address",
  5. "HTTPSPort": 1234
  6. ]
  7. configuration.connectionProxyDictionary = proxyConfiguration

相关问题