ios - ETag 和 If-None-Match HTTP header 不起作用

标签 ios swift nsurlsession etag if-none-match

我的网络服务器中有一个文件,我每次访问它时都会将其下载到我的应用程序中,因为文件内容可能会更改但如果更改了,我想在那个时候下载只有这样才能节省带宽,幸运的是,这就是 ETagIf-None-Match header fields 的用途。

  • 当我第一次发出请求时,我从 HTTP 响应 header 中检索 ETag

First time request to the file

  • 在随后的下载该文件的请求中,我将附加 If-None-Match header 字段的 Etag 值,以便如果没有变化则我将获得 HTTP 响应状态代码 304,否则如果文件发生更改,我将获得 200。

    Second time request for same file

注意:

当我在 chrome 的 Advanced REST Client Application 中尝试上述步骤时,它工作正常,但当我在 iOS 中尝试时,我总是得到响应代码 200,但它应该有给了我后续请求的 304。

这是我使用的示例代码

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)")

})

这是回复

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。您需要按如下方式设置:

request.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData

你会没事的

关于ios - ETag 和 If-None-Match HTTP header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608051/

相关文章:

ios - 顶部和底部带有淡入淡出单元格的 UITableView - swift

ios - 防止屏幕灯关闭 |在 watch 界面禁用 sleep 模式

ios - 如何在单击按钮时刷新 TableView

ios - 将 NSURLConnection 更改为 NSURLSession 后加载图像很慢

php - 通过 PHP 将 MySQL 记录发送到 iOS

objective-c - iOS/Objective-C : Creating a UIScrollView which fills screen and reorients

ios - swift: nsurlsession 下载文件

ios - MKMapView 和用户位置计时

ios - 在自定义 UICollectionViewCell 中更改 UILabel 的文本颜色

ios - 如何使用 NSURLSession 发布一些属性和图像