ios - 从 Swift 中的 HTTP 请求响应中检索 cookie
问题描述
第一次做苹果 swift 项目。我正在构建一个库,在其中向 API 发送 HTTP 请求,我需要检索响应中返回的 cookie,但由于某种原因,它们没有被检索到。
以下是我拥有的代码。
let url = URL(string: "http://192.168.1.118:500/initialise")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters: [String: String] = [
"ApplicationID": app_id,
"DeviceID": "123456",
"AppVersion": app_version
]
request.setValue(api_key, forHTTPHeaderField: "authorisation-token")
//request.httpBody = parameters.percentEscaped().data(using: .utf8)
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else {
print("error", error ?? "Unknown Error")
return
}
guard(200...299) ~= response.statusCode else {
print("statusCode should 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
print ("HTTP Status Code: " + String(response.statusCode))
print ("-------Cookies--------")
let cookieStorage = HTTPCookieStorage.shared
let cookies = cookieStorage.cookies(for: URL(string:"192.168.1.118:500")!) ?? []
for cookie in cookies {
if cookie.name == "SESSIONID" {
MyClass.SESSIONID = cookie.value
}
else if cookie.name == "DO-LB" {
MyClass.DOLB = cookie.value
}
}
我尝试将 cookieStorage.cookies URL 更改为包含和端口号 500 并排除它,但不幸的是,这两个都不起作用。
解决方案
推荐阅读
- ios - 如何使用 UIStackView 更改 UITableViewCell 的布局
- ubuntu-18.04 - Nextcloud 作为子域
- reactjs - Django-rest 框架、React JS、Axios- 发布包含图像文件的 JSON 数据
- machine-learning - 带逻辑回归的素数标识符
- git - 是否可以跟踪子模块内的文件?
- javascript - Javascript - 使用带有变量的 document.getelementbyid().value
- windows - 如何创建桌面快捷方式来启动 java JAR
- javascript - 如何根据第三个下拉列表项的选择切换不同的标签(下拉列表和列表)?
- sql - 将值与数据集中的前 n 个值进行比较
- python - 正在传递给 scipy.optimize.minimze 的函数的未知额外位置参数