我需要连接到HTTP代理后面的Web服务器。我尝试将URLSessionConfiguration
与connectionProxyDictionary
一起使用,但似乎忽略了我的代理配置,因为您可以将代理主机值更改为任何值,结果是相同的。
我尝试使用Charles Proxy来调试情况,而不是我需要连接的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()
在给定的示例中,我希望使用我在本地主机上设置的代理间接连接到ip.seeip.org:8888.
要点:https://gist.github.com/brunabaudel/90a6873d2c3df6caeb89f8b7afc9adce
2条答案
按热度按时间6yjfywim1#
kCFNetworkProxiesHTTP
键仅控制用于http
URL的代理。https
URL使用使用kCFNetworkProxiesHTTPS
密钥定义的代理。不幸的是,HTTPS密钥在iOS上不可用(真的不知道为什么),但实现已经存在,所以您只需传递带有正确密钥的字符串,即
"HTTPSEnable"
、"HTTPSProxy"
和"HTTPSPort"
。ecfsfe2w2#
非常感谢。以下代码可以正常工作: