ios - 重定向时未调用 URLSession willPerformHTTPRedirection
问题描述
我需要从请求中获取重定向 URL,我知道这样做的方法是在willPerformHTTPRedirection
.
当我尝试使用类似 URL 的代码时http://gmail.com
,重定向请求被注意到并通过willPerformHTTPRedirection
其他 URL 处理,重定向被处理但willPerformHTTPRedirection
未被调用。
例如,以下 URLhttps://www.pricecharting.com/search-products?q=045496590420&type=prices
不调用willPerformHTTPRedirection
. 如果我在 Postman 中关闭自动重定向,我可以在 Location 标头中看到重定向 URL。如何使用 URLSession 获取相同的信息?
class ViewController: UIViewController {
var session : URLSession?
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.pricecharting.com/search-products?q=045496590420&type=prices")!
var requestHeader = URLRequest.init(url: url)
requestHeader.httpMethod = "GET"
session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
session?.dataTask(with: requestHeader, completionHandler: { (data, response, error) in
if let response = response as? HTTPURLResponse {
if let l = response.value(forHTTPHeaderField: "Location") {
print("location", l)
}
print(response)
}
print("data is here")
print(response?.url)
}).resume()
}
}
extension ViewController: URLSessionTaskDelegate, URLSessionDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
print("stop redirect")
completionHandler(nil)
}
}
url 上的 curl 结果:
curl -i --head "https://www.pricecharting.com/search-products?q=045496590420&type=prices"
HTTP/1.1 307 Temporary Redirect
Content-Type: text/html; charset=utf-8
Location: https://www.pricecharting.com/game/nintendo-switch/zelda-breath-of-the-wild?q=045496590420
X-Appengine-Log-Flush-Count: 0
X-Cloud-Trace-Context: c2b9bab298c4d01e21a33759cdc99175
Date: Fri, 17 Sep 2021 23:06:21 GMT
Server: Google Frontend
Transfer-Encoding: chunked
解决方案
结果证明代码是正确的并且可以按需要工作。代码在调用之前出现。
我正在将条形码转换为 UPC,但我错误地将其转换为整数。整数不以 0 开头,UPC 以 0 开头。将 UPC 保留为字符串会保留 0。
鉴于此,以下 URL 可以正常工作,因为它的状态为 307:
https://www.pricecharting.com/search-products?q=045496590420&type=prices
此 URL 不是因为它的状态 200:
https://www.pricecharting.com/search-products?q=45496590420&type=prices
推荐阅读
- react-native - 如何将响应传递给 react-native RNPickerSelect 功能组件
- filter - GroupBy 函数不在 PowerApps 中显示图库磁贴
- amazon-ec2 - DBeaver 通过 SSH 隧道连接
- php - PHP:编写非 ASCII 字符,如德语变音符号 (öäü)
- azure - 在 Azure DevOps 中查找和删除重复的仪表板
- php - 如何访问此 PHP 对象中的特定键?
- javascript - JavaScript Graph 删除顶点
- python - Tensorflow,向顺序模型添加额外信息的最佳方法是什么?
- android - 同时在两个视图中约束 TextView
- java - 如何从java中的文件夹路径获取文件夹目录