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

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

问题描述

我想在标题请求中获得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

如Apple文档所述:

As apple documentation says :

一个字典,其中包含服务器响应中收到的所有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天全站免登陆