swift - allHeaderFields 在查找键时不区分大小写

标签 swift header alamofire

我正在使用 Alamofire 进行 API 调用。

根据我使用的服务器,响应 header 可以大写。

但是正如 allHeaderFields 的文档所说:

var allHeaderFields: [AnyHashable : Any] { get }

A dictionary containing all the HTTP header fields received as part of the server’s response. By examining this dictionary clients can see the “raw” header information returned by the HTTP server.

The keys in this dictionary are the header field names, as received from the server. See RFC 2616 for a list of commonly used HTTP header fields.

HTTP headers are case insensitive. To simplify your code, certain header field names are canonicalized into their standard form. For example, if the server sends a content-length header, it is automatically adjusted to be Content-Length.

The returned dictionary of headers is configured to be case-preserving during the set operation (unless the key already exists with a different case), and case-insensitive when looking up keys.

For example, if you set the header X-foo, and then later set the header X-Foo, the dictionary’s key will be X-foo, but the value will taken from the X-Foo header.

但是在我的代码中,如果我这样做:

if let headers = response.response?.allHeaderFields {
   print("Access-Token: \(response.response?.allHeaderFields["Access-Token"])")
   print("access-token: \(response.response?.allHeaderFields["access-token"])")
   print("access-token: \(response.response?.allHeaderFields["Access-token"])")
}

在我的控制台

Access-Token: nil
access-token: Optional(jdRtDzKHNs_i-jt3Lh3a3A)
access-token: nil

我错过了什么吗?

最佳答案

该错误与 Alamofire 无关。这是一个 Swift 错误。

不幸的是,这是 Swift 3 将 header 转换为字典时出现的已知错误。该漏洞自 2016 年以来一直存在,但至今仍未解决。更糟糕的是,他们甚至没有更正 Swift 文档。

这违反了 HTTP 规范,我不知道为什么他们只将其标记为中等优先级。似乎他们不关心也永远不会解决这个问题。

A workaround was made by Stephen Gurnett

Bug Report

关于swift - allHeaderFields 在查找键时不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324874/

相关文章:

swift - 如何对来自 Alamofire 的 JSON 进行排序并返回最终的 JSON 对象 (swiftyJSON)

ios - 在后台/屏幕外加载 WKWebView

ios - 迦太基更新时出现 Alamofire 错误

ios - 如何将圆形动画应用于单元格?

c - .h注释: previous declaration of 'QueueADT' was here typedef struct { } *QueueADT;

ios - 使用 ASIHTTPRequest 在重定向上附加原始 header

Swift:从一个 View 转换到另一个 View 时的动画效果

c++ - 不将 header 与实现分开是否仍然被认为是不好的做法?

ios - 带有 Alamofire 4 正文数据的 POST 请求

json - 如何使用 Alamofire 和 SwiftyJSON 访问嵌套 JSON 值?