从 POST 调用 URL 获取内容



我正在尝试从此 POST 调用中提取 cookie 以用于另一个调用。

我这里有一个 POST 调用的 URLSession 响应:

<NSHTTPURLResponse: 0x600000418120> { URL: https://example.com:443/Auth/ } { Status Code: 200, Headers {
Accept =     (
"*/*"
);
"Accept-Encoding" =     (
"br, gzip, deflate"
);
"Accept-Language" =     (
"en-us"
);
Authorization =     (
"Basic keyHere=="
);
"Content-Encoding" =     (
gzip
);
"Content-Type" =     (
"application/json"
);
Date =     (
"Tue, 25 Sep 2018 18:17:38 GMT"
);
Host =     (
"example.com:443"
);
"SMSESSION-Idle-Expire" =     (
"Tue, 25-Sep-2018 20:17:38 GMT"
);
"SMSESSION-Session-Expire" =     (
"Wed, 26-Sep-2018 04:17:38 GMT"
);
"Set-Cookie" =     (
"SMSESSION=sessionKeyHere==;Domain=example.com;Path=/"
);
"Transfer-Encoding" =     (
Identity
);
"User-Agent" =     (
"Web%20Service%20Test/1 CFNetwork/974.2.1 Darwin/18.0.0"
);
"X-Forwarded-For" =     (
"11.111.11.11"
);
} }

如何从这里提取 Set-Cookie SMSESSION 密钥?有没有正确的方法可以做到这一点?还是我只是解析此响应并从那里提取密钥?

这是我的函数:

func test() {
let username = "myUsername"
let password = "myPassword"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
let url = URL(string: "https://example.com:443/Auth/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic (base64LoginString)", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}

感谢您的帮助!

感谢@Cristik的回答。

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
let httpResponse = response as! HTTPURLResponse // HTTPURLResponse is a subclass of URLResponse
print(httpResponse.allHeaderFields["Set-Cookie"] ?? "") // Cookie Value
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()

相关内容

  • 没有找到相关文章

最新更新