我正在努力阅读 Content-Length
响应,但它总是跳过,没有得到响应。即使是最简单的一个。我使用了不同的URL链接来检查,但结果是一样的,每次都跳过,没有响应。
URL链接: calculateLength(Link: "")
编码。
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"
);
} }
对于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)
}
}
}
}
进入 HTTPURLResponse
的财产 value
(适用于iOS 13及以上版本)或 allHeaderFields
按照iOS版本。你只需要传递密钥名称,即是 "Content-Length"
在你的情况下。
extension HTTPURLResponse {
func valueForHeaderField(_ headerField: String) -> String? {
if #available(iOS 13.0, *) {
return value(forHTTPHeaderField: headerField)
} else {
return (allHeaderFields as NSDictionary)[headerField] as? String
}
}
}
你可以调用上面的函数,比如
let contentLegth = response.response.valueForHeaderField("Content-Length")