有没有办法用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
答案 0 :(得分:4)
由于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")
}
}
}
答案 1 :(得分:0)
您可以按照here概述的Alamofire使用手动回复验证。
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}