ios - 如何使用 Swift 5 的代理配置连接到 HTTP 服务器(为什么忽略 connectionProxyDictionary)?
问题描述
我需要连接到 HTTP 代理后面的网络服务器。我试过使用URLSessionConfiguration
with 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
解决方案
这些kCFNetworkProxiesHTTP
键仅控制用于http
URL 的代理。https
URL 使用通过kCFNetworkProxiesHTTPS
键定义的代理。
不幸的是,HTTPS 密钥在 iOS 上不可用(真的不知道为什么),但实现在那里,所以你可以使用正确的密钥传递字符串,即"HTTPSEnable"
,"HTTPSProxy"
和"HTTPSPort"
.
推荐阅读
- python - How to prevent 'HTTPS NOT SUPPORTED' Error in youtube-dl by validating video Ids?
- python - 如何对网页中的动态元素执行操作
- c# - 如何检测 Unity 中发生碰撞的位置?
- reactjs - 获取为每个文档读取的集合的所有文档?
- javascript - Find all occurrences of elements in an array in a string
- kubernetes - 尝试连接到 Kubernetes 中的排序服务时连接被拒绝
- python-3.x - Geopandas Spatial Join - AttributeError: 'NoneType' object has no attribute 'bounds'
- python - 如何在 django view.py 中连接字符串和变量?
- python - 使用 Django 使用 PayPal 完成付款后获取信息
- ansible - 没有与 atomic-openshift-utils 匹配的包