如何在Swift中获取HTTP请求头?

kgqe7b3p  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(129)

我正在尝试获取在端点获取的cookie和授权令牌
提供的curl命令是:curl 'url.com' -XGET -I
如何在Swift中获取header中的请求响应?
我是一个使用Swift网络的新手,我试着在Stackoverflow上四处寻找,但没有运气。

zbdgwd5y

zbdgwd5y1#

我自己也是个新手。让我试着帮你。

func getCookiesAndAuthToken(_ url: URL?) {
    guard let url else { return }
    var request = URLRequest(url: url)
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        // If error, exits the program
        guard error == nil else { print(error as Any); return }
        // typecast response to HTTPURLResponse so that we can access its property allHeaderFields a.k.a "headers"
        guard let httpResponse = response as? HTTPURLResponse else { print("could not typecast to HTTPURLResponse"); return }
        // typecast allHeaderFields to String: String Dictionary
        guard let fields = httpResponse.allHeaderFields as? [String: String] else { print("Error with headers"); return }
        // get your authorization token here
        // it probably is in the headers
        for (_, field) in fields.enumerated() {
            // ACTIONS REQUIRED FROM YOU:
            // do something here to match field's key so that you get the authorization token
            print(field)
        }
        // Space Between Token and Cookie infos
        for _ in 0...3 { print() }
        // get your cookies here
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: (response?.url)!)
        // THESE ARE THE COOKIES THAT YOU WANT FROM THE WEBSITE THAT YOU VISITED ABOVE
        for cookie in cookies {
            print("name: \(cookie.name) value: \(cookie.value)")
        }
    }
    task.resume()
}

字符串

编辑

如果你想要一个类似Python库请求的请求-响应,那么上面的就是答案。也许你需要像下面这样的请求头?但不确定。

func getCookiesAndAuthToken(_ url: URL?) {
    guard let url else { return }
    var request = URLRequest(url: url)
    guard let fields = request.allHTTPHeaderFields else { print("Error with headers"); return }
    // get your authorization token here
    // it probably is in the headers
    for (_, field) in fields.enumerated() {
        // ACTIONS REQUIRED FROM YOU:
        // do something here to match field's key so that you get the authorization token
        print(field)
    }
}

相关问题