gpt4 book ai didi

ios - 如何使用 Alamofire 检测 304 statusCode

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:53 30 4
gpt4 key购买 nike

有没有办法用 Alamofire 4 检测 304 Not Modified 响应?我发现 Alamofire response.statusCode 始终为 200,即使服务器响应为 304。

网络通话设置:

Alamofire 
.request("http://domain.com/api/path", method: .get)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
print(response.response?.statusCode)
}

Alamofire 响应头

<NSHTTPURLResponse: 0x61800003e1c0> { URL: http://domain.com/api/path } { status code: 200, headers {
"Access-Control-Allow-Headers" = "content-type, authorization";
"Access-Control-Allow-Methods" = "GET, PUT, POST, DELETE, HEAD, OPTIONS";
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "private, must-revalidate";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Mon, 23 Jan 2017 23:35:00 GMT";
Etag = "\"f641...cbb6\"";
"Proxy-Connection" = "Keep-alive";
Server = "nginx/1.10.1";
"Transfer-Encoding" = Identity;
} }

服务器响应

HTTP/1.1 304 Not Modified
Server: nginx/1.10.1
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Cache-Control: private, must-revalidate
ETag: "f641...cbb6"
Date: Mon, 23 Jan 2017 23:35:00 GMT

最佳答案

由于 NSURLSessions 的默认行为是通过始终返回 200 个响应(而不是实际重新加载数据)从缓存的 304 响应中抽象出来,我首先必须按如下方式更改 cachingPolicy:

urlRequest.cachePolicy = .reloadIgnoringCacheData

然后,我调整了 validate 函数的状态代码以接受 3xx 响应并相应地处理代码:

Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<400)
.responseData { response in
switch response.response?.statusCode {
case 304?:
print("304 Not Modified")
default:
switch response.result {
case .success:
print("200 Success")
case .failure:
print ("Error")
}
}
}

关于ios - 如何使用 Alamofire 检测 304 statusCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41816606/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com