首页 > 解决方案 > 如何使用 Alamofire Swift 读取 Content-Length HTTPResponse

问题描述

我试图Content-Length从响应中读取,但它总是跳过并且没有得到响应。即使是最简单的。我使用了不同的 URL 链接进行检查,但每次跳过的结果都是相同的,并且没有响应。

网址链接:calculateLength(链接:“”)

代码:

func calculateLength(Link: String)  {
        Alamofire.request(Link, method: .get, parameters: nil, encoding: URLEncoding.httpBody).responseJSON
                    { response in
                        //to get JSON return value
                        if let ALLheader = response.response?.allHeaderFields  {
                            if let header = ALLheader as? [String : Any] {
                                if let contentLength = header["Content-Length"] as? String {

                                }
                            }
                        }
        }
    }

从服务器获取响应:

(Response) <NSHTTPURLResponse: 0x6000000c7120> { URL:  } { Status Code: 200, Headers {
    "Cache-Control" =     (
        private
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        837
    );
    "Content-Type" =     (
        "text/html"
    );
    Date =     (
        "Thu, 21 May 2020 08:04:55 GMT"
    );
    Server =     (
        "Microsoft-IIS/8.5"
    );
    "Set-Cookie" =     (
        "ASPSESSIONIDSSSCCBAB=AKDPKPMCKNDJPANFODFAJKAH; path=/"
    );
    Vary =     (
        "Accept-Encoding"
    );
    "X-Powered-By" =     (
        "ASP.NET"
    );
} }

标签: iosswiftalamofirehttpresponse

解决方案


对于 Alamofire 5,您的函数将如下所示:

func calculateLength(link: String) {
     AF.request(link, method: .get).response() { response in
         if let headers = response.response?.headers  {
             print(headers.value(for: "Content-Length"))
         }
     }
}

对于 Alamofire 4,它会是这样的

func calculateLength(link: String) {
     Alamofire.request(link, method: .get).responseJSON { response in
         if let headers = response.response?.allHeaderFields as? [String : Any] {
             if let contentLength = headers["Content-Length"] as? String {
                 print(contentLength)
             }
         }
     }
}

推荐阅读