从swift中的请求响应中获取头数据

8 api rest http-headers swift

我想在一个标题请求中获得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;
Run Code Online (Sandbox Code Playgroud)

kam*_*soc 15

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

正如苹果文档所说:

包含作为服务器响应的一部分接收的所有HTTP头字段的字典.通过检查此字典,客户端可以看到HTTP服务器返回的"原始"标头信息.

此字典中的键是从服务器接收的标题字段名称.有关常用HTTP头字段的列表,请参阅RFC 2616.

因此,要获得响应标头中的X-Dem-Auth,您可以通过以下方式访问它:

if let httpResponse = response as? NSHTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

由于Evan R的评论而更新

if let httpResponse = response as? HTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 它现在被称为 `HTTPURLResponse` 而不是 `NSHTTPURLResponse`。 (2认同)