swift - 快速从请求响应中获取 header 数据

标签 swift api rest http-headers

我想在 header 请求中获取 X-Dem-Auth,并 swift 将其存储在我的应用中。

查看回复:

headers {
    "Content-Length" = 95;
        "Content-Type" = "application/json; charset=utf-8";
        Date = "Fri, 15 Apr 2016 08:01:58 GMT";
        Server = "Apache/2.4.18 (Unix)";
        "X-Dem-Auth" = null;
        "X-Powered-By" = Express;

最佳答案

如果响应是 NSHTTPURLResponse 类型,您可以从 response.allHeaderFields 获取 header

正如苹果文档所说:

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.

因此,例如,要在响应 header 中获取 X-Dem-Auth,您可以通过这种方式访问​​它:

if let httpResponse = response as? NSHTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}

更新

根据 Evan R 的评论更新

if let httpResponse = response as? HTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}

关于swift - 快速从请求响应中获取 header 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641700/

相关文章:

excel - 使用 Excel 中的 Web 服务功能使用 Yahoo API 从 Yahoo Finance 提取 "Next Earnings Date"

api - YouTube API请求访问给定日期的视频观看次数?

java - CXF 贾克斯 |生成的 wadl 中不存在复杂的响应类型

java - JAX-RS Jersey 处理 WebApplicationException

ios - 执行自定义 segue 时调用不平衡

ios - 在 UITableView 上执行具有多个状态的 segue 的问题

c# - 有没有办法通过 DropNet 获取文件之间更改的字节?

java - Jackson JSON 动态键值绑定(bind)到 Java Bean

objective-c - 使用 **void 参数从 swift 访问 objective-c 函数

json - ARKit 4.0 – 是否可以将 ARWorldMap 数据转换为 JSON 文件?