如何在Swift中解析HTTPHeader

时间:2019-12-22 07:52:59

标签: swift http-headers

我想编写一个Swift脚本来使用摘要身份验证对Rest Server进行身份验证。我不会使用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。但是,我该如何读取随机数或标题的其他部分。如果我打电话给print (head.headers.contains(name: "nonce")),我得到的结果是假的。 head是HTTPResponseHead的对象。我是否要手动解析Header或存在要读取的Header,然后创建用于身份验证的哈希值。

1 个答案:

答案 0 :(得分:0)

尝试使用此方法。

 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”