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

时间:2023-02-05 21:13:05

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

我想在一个标题请求中获得X-Dem-Auth,swift在我的应用程序中存储它。

See the response :

看到回复:

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;

1 个解决方案

#1


8  

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

如果响应是NSHTTPURLResponse的类型,则可以从response.allHeaderFields获取标头

As apple documentation says :

正如苹果文档所说:

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标头字段的字典。通过检查此字典,客户端可以看到HTTP服务器返回的“原始”标头信息。

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头字段的列表,请参阅RFC 2616。

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

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

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

UPDATE

UPDATE

Updated due to comment from Evan R

由于Evan R的评论而更新

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

#1


8  

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

如果响应是NSHTTPURLResponse的类型,则可以从response.allHeaderFields获取标头

As apple documentation says :

正如苹果文档所说:

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标头字段的字典。通过检查此字典,客户端可以看到HTTP服务器返回的“原始”标头信息。

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头字段的列表,请参阅RFC 2616。

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

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

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

UPDATE

UPDATE

Updated due to comment from Evan R

由于Evan R的评论而更新

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