Problems with caching using NSURLConnection and querying HTTP Headers
I am trying to write a crude app to loop round querying some of the HTTP Header fields that come back from my server in order to find out which servers are responding OK. My servers respond with a header like this: server = server1 (or server2, server 3 etc).
Unfortunately when I do this I get the same server name back time and time again from the app unless I stop i开发者_如何学编程t and run it again at which point I get a different server back. How can I stop this happening? I need the app to treat each connection as if it is brand new, but it seems to cache something and appear to come from the same place, so my load balancer returns the same server name.
I can replicate similar behaviour(expected) in Safari by going to my URL repeatedly without shutting down Safari - it gets the same server each time, but if I shut down Safari then go back into it I get a new server.
The code I am using is as follows:
for (int i = 0; i < 999; i++) {
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
dictionary = [response allHeaderFields];
fullHeaderString = [dictionary description];
}
}
How can I make this connection be treated like a new one every time?
Cheers, Tom
You can make sure the content is freshly loaded each time in at least 2 ways:
- Add the "pragma: no-cache" header to your http response. This should make the http client not cache the response.
- Add a random query parameter to the request like: url = "http://myhost.com/controller/blabla?rand=" + Math.random(...). This would make the url unique each time but the server would probably not care about the parameter so it would still be safe.
Hope this helps
I was having the exact same problem, but I just figured it out after reading your post, so I thought i'd share what I learned.
In connection:didReceiveData:
I was appending the incoming bytes to an NSData object in the delegate. However, I was not clearing out that buffer in between requests: i was merely appending data to the end of it. My parsing algorithm simply looked for the first instance of the xml response and passed it back, which means it was passing back the OLD data.
In conclusion, the system wasn't doing any caching; I was.
The solution: before you make each call clear out your data:
[myData setData:[NSData data]];
Hope that this works for you. I know it's saving a huge headache on my end.
精彩评论