快速从请求响应中获取标头数据 [英] Get header data from a request response in swift

查看:31
本文介绍了快速从请求响应中获取标头数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在标头请求中快速获取 X-Dem-Auth 以将其存入我的应用中.

I want to get X-Dem-Auth in a header request with swift to stock that in my app.

查看回复:

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

If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields

正如苹果文档所说:

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

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.

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

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.

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

So to get for example a X-Dem-Auth in response header you can access it in that way :

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

更新

根据 Evan R 的评论更新

Updated due to comment from Evan R

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

这篇关于快速从请求响应中获取标头数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆