ios - 如何使用 Alamofire Swift 读取 Content-Length HTTPResponse
问题描述
我试图Content-Length
从响应中读取,但它总是跳过并且没有得到响应。即使是最简单的。我使用了不同的 URL 链接进行检查,但每次跳过的结果都是相同的,并且没有响应。
- 甚至可以使用任何 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"
);
} }
解决方案
对于 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)
}
}
}
}
推荐阅读
- git - 试图从功能分支中挑选:没有“樱桃”?
- sql - 使用 HQL 计算两个字段的差异之间的范围
- nginx - nginx 从 x-forwarded 获取源客户端 ip 以使用 map 模块
- java - 无法在杰克逊 xml 中序列化 OffsetDateTime
- java - Selenium Webdriver:拖放不起作用
- typescript - 如何在 Vue 模板中为来自 Apollo 的数据启用 Typescript 输入(VS Code)
- java - java.lang.IllegalStateException: getOutputStream() 已经为此响应调用 - SpringBoot
- php - 如何使用 foreach 循环为图像幻灯片创建分页
- html - 内容 div 高于里面的元素
- javascript - 嵌套数组操作