首页 > 解决方案 > 我在我的 URLSession 中添加了一个 cookie,但我的 URLRequest 中缺少它

问题描述

我遇到了 URLSession URLRequest 中的 cookie 问题。我有一个 Swift Playground,我在其中向我的 URLSession 添加了一个 cookie,我希望在对本地服务器的请求中看到它,但它不存在。我错过了什么?这是我的游乐场:

import Foundation
let config = URLSessionConfiguration.default
config.httpCookieStorage?.setCookie(
    HTTPCookie(properties: [
        HTTPCookiePropertyKey.domain: "http://localhost:8000",
        HTTPCookiePropertyKey.path: "/",
        HTTPCookiePropertyKey.name: "Eugene",
        HTTPCookiePropertyKey.value: "Test",
        HTTPCookiePropertyKey.secure: "TRUE",
        HTTPCookiePropertyKey.expires: Date(timeIntervalSinceNow: 1000000)
    ])!
)
config.httpShouldSetCookies = true
config.httpCookieAcceptPolicy = .always
let session = URLSession(configuration: config)
print(session.configuration.httpCookieStorage?.cookies)
var request = URLRequest(url: URL(string: "http://localhost:8000")!)
let task = session.dataTask(with: request) { data, urlResponse, error  in
    print(data)
    print(urlResponse)
    print(error)
}
task.resume()

这是我操场的输出:

Optional([<NSHTTPCookie
    version:0
    name:Eugene
    value:Test
    expiresDate:'2021-06-05 15:25:19 +0000'
    created:'2021-05-25 01:38:39 +0000'
    sessionOnly:FALSE
    domain:http://localhost:8000
    partition:none
    sameSite:none
    path:/
    isSecure:TRUE
 path:"/" isSecure:TRUE>])
Optional(1318 bytes)
Optional(<NSHTTPURLResponse: 0x6000005c5500> { URL: http://localhost:8000/ } { Status Code: 200, Headers {
    "Content-Length" =     (
        1318
    );
    "Content-Type" =     (
        "text/html; charset=utf-8"
    );
    Date =     (
        "Tue, 25 May 2021 01:38:40 GMT"
    );
    Server =     (
        "SimpleHTTP/0.6 Python/3.8.2"
    );
} })
nil

这是服务器看到的请求,明显缺少 Cookie 标头:

127.0.0.1 - - [24/May/2021 20:38:40] "GET / HTTP/1.1" 200 -
ERROR:root:Host: localhost:8000
Accept: */*
Accept-Language: en-us
Connection: keep-alive
Accept-Encoding: gzip, deflate
User-Agent: URLSession/1 CFNetwork/1220.1 Darwin/20.3.0

标签: swiftnsurlsession

解决方案


一个问题可能是 Swift Playground 至少在历史上与 NSURLSession 相处得并不融洽。这现在可能已修复,在这种情况下没关系,但如果没有,那么您可以尝试在实际应用程序中执行此操作。

第二个问题是 cookie 上的 isSecure 属性已设置,但您正试图通过 HTTP(不安全)发送 cookie,因此它永远不会被发送。

最后,localhost 本身可能有问题。请参阅具有显式域的 localhost 上的 Cookie。我不知道 Apple 的 cookie 存储是如何处理这种边缘情况的,但无论如何你都应该意识到这一点。


推荐阅读