gpt4 book ai didi

swift - 如何在 Swift 中解析 HTTPHeader

转载 作者:行者123 更新时间:2023-11-30 10:29:20 24 4
gpt4 key购买 nike

我想编写一个 Swift 脚本来通过摘要身份验证对 Rest 服务器进行身份验证。我不会使用 URLSession,我想手动完成。我从服务器收到第一个响应,如下所示:

[
("Connection", "close"),
("Date", "Sun, 22 Dec 2019 07:36:50 GMT"),
(
"WWW-Authenticate",
"Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"
),
(
"Cache-Control",
"must-revalidate,no-cache,no-store"
),
(
"Content-Type",
"text/plain;charset=utf-8"
),
("Content-Length", "16"),
("Server", "Jetty(9.4.19.v20190610)")
]

我在 Swift 中得到一个对象 HTTPResponseHead。但是我如何读取 header 的随机数或其他部分。如果我调用 print (head.headers.contains(name: "nonce")) ,我会得到错误的结果。 head 是 HTTPResponseHead 的对象。我是否手动解析 header ,或者存在读取 header ,然后创建用于身份验证的哈希值。

最佳答案

用这个方法试试。

 func getAuthenticationKey(headerInfo: [(String, String)]) -> String?{
for item in headerInfo.enumerated(){
print("key: \(item.element.0), values : \(item.element.1)")

let headerKeys = item.element.1.split(separator: ",")

for item in headerKeys {
if item.contains("nonce") {
let authinticationKey = item.split(separator: "=")[1]
return String(authinticationKey)
}
}

}
return nil
}

使用:

 let headerInfo = [("Connection", "close"), ("Date", "Sun, 22 Dec 2019 07:36:50 GMT"), ("WWW-Authenticate", "Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"), ("Cache-Control", "must-revalidate,no-cache,no-store"), ("Content-Type", "text/plain;charset=utf-8"), ("Content-Length", "16"), ("Server", "Jetty(9.4.19.v20190610)")]
print(getAuthenticationKey(headerInfo: headerInfo))

输出:

"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz"

关于swift - 如何在 Swift 中解析 HTTPHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com