如何检索请求的Alamofire响应头

时间:2021-05-10 13:43:58

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!

提前致谢!

1 个解决方案

#1


31  

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

如果响应是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. 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 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
}

#1


31  

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

如果响应是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. 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 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
}