ETag and If-None-Match HTTP Headers Not Working

I have a file on my web server, and I upload it to my application every time I access it, because its possible change to the contents of the file may be changed. But if it has changed, I would like to download this time only so that the bandwidth can be saved and, fortunately, for this ETag and If-None-Match header fields.

  • When I make a request for the first time, I extract the ETag from the headers of the HTTP response

First time request to file

  • In subsequent requests to download this file, I would bind the Etag value for the If-None-Match header field, so that if there are no changes, I would get an HTTP response code 304, otherwise I would get 200 if there is a change in the file.

    Second time request for the same file

Note:

When I try to follow the above steps in the REST Advanced Client Application in chrome, it works fine as expected, but when I try to do this in iOS, I always get a 200 response code, but it should have given me 304 for subsequent requests.

Here is an example of the code I'm using

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

Here's the answer

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 change "=" Fri, February 19, 2016 10:15:33 GMT "; Server =" Apache / 2.4.16 (Unix) PHP / 5.5.29 ";}})

What am I doing wrong here?

+5
source share
2 answers

I ran into the same problem. I found that this is due to cachePolicy . You should install it as follows:

 request.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData 

And you will be fine

+5
source

The CachePolicy naming convention is confusing and better, but it doesn't actually implement some of them ...

In this article, they are well explained. http://nshipster.com/nsurlcache/

In addition, if you allow the cache policy to use UseProtocolCachePolicy , then your NSURLSession will receive a status code of 200 with a response generated from the cache.

0
source

Source: https://habr.com/ru/post/1243772/


All Articles