ETag和If-None-Match HTTP标头不起作用 [英] ETag and If-None-Match HTTP Headers are not working
问题描述
我的 webserver 中有一个文件,我每次访问它时都会将其下载到我的应用程序,因为它可能会更改文件内容但是如果它被更改我想下载那个时间只有这样才能保存带宽,幸运的是,这个 ETag 和 If-None-Match 标题字段的目的是什么。
I have a file in my webserver and I am downloading that to my app everytime I access it because its possible that file content might be changed But If it is changed I would like to download that time only so bandwidth can be saved and fortunately that's what this ETag and If-None-Match header fields are for.
- 当我第一次提出请求时,我从HTTP响应标题中检索 ETag
- When I make a request first time ,I retrieve the ETag from the HTTP response headers
-
在随后的下载该文件的请求中,我附加 If-None-Match 标题字段的 Etag 值,这样如果没有变化,那么我会得到HTTP响应状态代码304,否则如果文件发生变化,我会得到200.
In the subsequent requests to download that file I'd attach the Etag value for If-None-Match headerfield so that if there is no change then I'd get HTTP response status code 304 or else I'd get 200 if there is a change in the file.
注意:
当我在chrome中的高级REST客户端应用程序中尝试上述步骤时,它可以正常工作,但是当我在iOS中尝试时,我总是得到响应代码200但它应该有给我304后续请求。
When I try the above steps in Advanced REST Client Application in chrome it works fine as it is supposed to be but when I try that in iOS I always get the response code 200 but it should have given me 304 for the subsequent requests.
以下是我使用的示例代码
Here is the sample code I use
var request1 = NSMutableURLRequest(URL:NSURL(string: "http://10.12.1.101/Etag/ringtone1.mp3")!)
let Etagvalue="\"36170-52c1cc36d9b40\""
var session1 = NSURLSession.sharedSession()
request1.HTTPMethod = "GET"
var err: NSError?
request1.addValue(Etagvalue, forHTTPHeaderField: "If-None-Match")
var task = session1.dataTaskWithRequest(request1, completionHandler: {data, response, error -> Void in
print("response: \(response)")
})
以下是回复
回复:可选({URL:
http://10.12.1.101/Etag/ringtone1.mp3 } {状态代码:200,标题{
接受 - 范围=字节;
连接=保持活跃;
内容长度= 221552;
内容类型=音频/ mpeg;
日期=星期三,2016年2月24日14:57:53 GMT;
Etag =\36170-52c1cc36d9b40 \;
Keep-Alive=timeout = 5,max = 100;
Last-Modified=星期五,2016年2月19日10:15:33 GMT;
Server =Apache / 2.4.16(Unix)PHP / 5.5.29;} })
response: Optional( { URL: http://10.12.1.101/Etag/ringtone1.mp3 } { status code: 200, headers { "Accept-Ranges" = bytes; Connection = "Keep-Alive"; "Content-Length" = 221552; "Content-Type" = "audio/mpeg"; Date = "Wed, 24 Feb 2016 14:57:53 GMT"; Etag = "\"36170-52c1cc36d9b40\""; "Keep-Alive" = "timeout=5, max=100"; "Last-Modified" = "Fri, 19 Feb 2016 10:15:33 GMT"; Server = "Apache/2.4.16 (Unix) PHP/5.5.29"; } })
我在做什么在这里?
推荐答案
我遇到了同样的问题。我发现这是因为 cachePolicy
。您需要按如下方式设置:
I've encountered the same problem. I've discovered that it's because of cachePolicy
. You need to set it as follows:
request.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
你会没事的
这篇关于ETag和If-None-Match HTTP标头不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!