简体   繁体   English

如何检索请求的Alamofire响应头

[英]How to retrieve Alamofire response header for a request

how can I retrieve response headers for a request? 如何检索请求的响应标头? Below is a request I make. 以下是我提出的要求。

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
        .responseJSON { response in switch response.result {
        case .Success(let JSON):

            ...

        case .Failure(let error):

            ...

    }

Thanks in advance! 提前致谢!

If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields . 如果响应是NSHTTPURLResponse类型, NSHTTPURLResponse可以从response.allHeaderFields获取标头。

So when you use Alamofire responseJSON you can access to NSHTTPURLResponse property like this : 因此,当您使用Alamofire responseJSON时,您可以访问NSHTTPURLResponse属性,如下所示:

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers).responseJSON {
        response in
        print(response.response?.allHeaderFields)
}

As apple documentation says : 正如苹果文档所说:

A dictionary containing all the HTTP header fields received as part of the server's response. 包含作为服务器响应的一部分接收的所有HTTP头字段的字典。 By examining this dictionary clients can see the “raw” header information returned by the HTTP server. 通过检查此字典,客户端可以看到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 content-type in response header you can access it in that way : 因此,要获得响应头中的内容类型,您可以通过以下方式访问它:

if let contentType = response.response?.allHeaderFields["Content-Type"] as? String {
        // use contentType here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM