重定向时未调用 URLSession willPerformHTTPRedirection

URLSession willPerformHTTPRedirection not called on redirect

我需要从请求中获取重定向 URL,我知道这样做的方法是 willPerformHTTPRedirection

当我尝试使用像 http://gmail.com 这样的 URL 代码时,重定向请求通过 willPerformHTTPRedirection 而不是其他 URL 被注意到和处理,重定向被处理但是 willPerformHTTPRedirection 没有被调用。

例如下面的URLhttps://www.pricecharting.com/search-products?q=045496590420&type=prices不调用willPerformHTTPRedirection。如果我在 Postman 中关闭自动重定向,我可以在位置 header 中看到重定向 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)
    
}
}

curl url 的结果:

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