【问题标题】:How to get cookies from URLSession response in Swift如何从 Swift 中的 URLSession 响应中获取 cookie
【发布时间】:2019-07-23 14:21:49
【问题描述】:

这是我第一次问。

我正在使用 Swift 5。 我正在做一个登录功能,所以我需要使用 Cookie 保存“JSESSIONID”,所以我试图从响应头的 Set-Cookie 参数中读取数据,但我无法获取任何数据。如何获取数据?

我检查了“Set-Cookie”是由 servlet 使用 curl 命令发送的。我附上了一个响应头。

jun-MacBook-Pro:~ junki-t$ curl -X POST -D - -d "SOME PARAMETERS" http://example.com/PATH/UserProfilingService
HTTP/1.1 302 Found
Date: Tue, 23 Jul 2019 10:49:02 GMT
Set-Cookie: JSESSIONID=91********************BA; Path=/******; HttpOnly
Location: /?AUTHORIZED=yes&USERPROFILEKEY=*********
Content-Length: 0
Connection: close
Content-Type: text/plain

jun-MacBook-Pro:~ junki-t$ 

我尝试在 Swift 应用程序中转储响应数据,但未找到“Set-Cookie”。

- some: <NSHTTPURLResponse: 0x281050860> { URL: http://example.com/?AUTHORIZED=yes&USERPROFILEKEY=********* } { Status Code: 200, Headers {
    "Accept-Ranges" =     (
        bytes
    );
    Connection =     (
        close
    );
    "Content-Length" =     (
        146
    );
    "Content-Type" =     (
        "text/html"
    );
    Date =     (
        "Wed, 17 Jul 2019 08:51:38 GMT"
    );
    Etag =     (
        "\"92-5********a3\""
    );
    "Last-Modified" =     (
        "Wed, 30 Nov 2016 07:44:17 GMT"
    );
    Server =     (
        Apache
    );
} } #0
    - super: NSURLResponse
      - super: NSObject
func tryAuth() {
    let id = "*****"
    let pass = "*****"

    let url = URL(string: "<Some url>")
    var url_request = URLRequest(url: url!)
    url_request.httpMethod = "POST"
    url_request.httpShouldHandleCookies = true

    let body = "SOME PARAMETERS FOR AUTHENTICATE"
    url_request.httpBody = body.data(using: String.Encoding.utf8)

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

    session.dataTask(with: url_request).resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
    let httpResponse = response as? HTTPURLResponse
    var dict = httpResponse?.allHeaderFields
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: httpResponse?.allHeaderFields as! [String : String], for: response.url!)
    dump(cookies) // for testing.
    //
    // some process to get/save cookie.
    //
}

我认为cookies有一些数据(我想得到“JSESSIONID”),但是cookies有0个元素。

所以我无法获取任何 cookie 数据。

【问题讨论】:

  • 在您转储的响应中,"Content-Length" 是 146 个字符,而在成功的 curl 响应中,它是 Content-Length: 0。那么该响应包含什么? (可能是错误?)
  • 我检查了我的回复,重定向前的页面内容长度为0,但重定向后的页面有146个字符,没有错误。我认为 curl 在重定向之前显示 HTTP 响应标头,但 URL 会话在重定向后返回 HTTP 响应标头。

标签: swift urlsession httpcookie


【解决方案1】:

来自HTTPCookieAcceptPolicy 文档:

此属性根据此配置确定会话中所有任务的 cookie 接受策略。默认值为 NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain。您可以将其更改为 NSHTTPCookieAcceptPolicy 枚举类型中定义的任何常量。如果您想更直接地控制接受哪些 cookie,请将此值设置为 NSHTTPCookieAcceptPolicyNever,然后使用 allHeaderFields 和 cookiesWithResponseHeaderFields:forURL: 方法自行从 URL 响应对象中提取 cookie。

所以,你需要设置session.configuration.httpCookieAcceptPolicy = .never,或者如果你想让系统自动设置cookies,你可以使用HTTPCookieStorage.shared.cookies(for: response.url)

【讨论】:

猜你喜欢
  • 2021-07-30
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2019-01-23
相关资源
最近更新 更多