【问题标题】:How to get cookie with URLSession request?如何通过 URLSession 请求获取 cookie?
【发布时间】:2019-09-09 12:20:46
【问题描述】:

我正在使用 URLSession 发送一个请求。我收到了响应,但 HTTPCookieStorage.shared.cookies 的值始终为 0 元素。我是iOS模拟器中的测试。

    guard let url = URL(string: "https://10.10.224.30/sdc/v2/common/token") else {
        return
    }
    let configuration = URLSessionConfiguration.default
    configuration.httpCookieAcceptPolicy = .always

    let mySession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    var request = URLRequest(url: url)
    request.setValue("OTT_CLIENT", forHTTPHeaderField: "User-Agent")
    request.setValue("Basic aHR0cHdhdGNoOmY=", forHTTPHeaderField: "Authorization")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("11044", forHTTPHeaderField: "X-Device-Identifier")
    request.setValue("Deflate/gzip/compress",
                     forHTTPHeaderField: "Accept-Encoding")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"

    var urlParser = URLComponents()
    urlParser.queryItems = [
        URLQueryItem(name: "scope", value: "OpenId ONEApp"),
        URLQueryItem(name: "username", value: "2345679091"),
        URLQueryItem(name: "grant_type", value: "password"),
        URLQueryItem(name: "audience", value: "https://login.account.rakuten.com"),
        URLQueryItem(name: "nonce", value: "a1b2c3")

    ]
    let httpBodyString = urlParser.percentEncodedQuery
    request.httpBody = httpBodyString?.data(using: String.Encoding.utf8)

    let task = mySession.dataTask(with: request) { (data, response, error) in

        if let httpResponse = response as? HTTPURLResponse {
            let fields = httpResponse.allHeaderFields as! [String : String]
            var cookies1 =  URLSession.shared.configuration.httpCookieStorage?.cookies

            print(cookies1)

        }

    task.resume()

【问题讨论】:

    标签: urlsession httpcookie


    【解决方案1】:

    您可以通过将 httpCookieStorage 设置为任何共享对象或您的对象来做到这一点

        let config = URLSessionConfiguration.default
        config.httpCookieAcceptPolicy = .always
        config.httpShouldSetCookies = true
        config.httpCookieStorage = HTTPCookieStorage.shared
        let mySession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    

    然后作为响应,您可以获取

      if let cookies = HTTPCookieStorage.shared.cookies(for: responseURL) {
                            print(cookies)
                        }
    

    您将获得 cookie 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2014-12-09
      • 2019-06-20
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      相关资源
      最近更新 更多