views:

321

answers:

2

I have the below code, which simply downloads a file and saves it. I want to run it every 30 seconds and check if the remote-file's mtime has changed and download it if it has. I'll be creating a thread which sleeps 30seconds after every iteration of an endless loop for that purpose, but; how do I check a remote file's mtime without downloading it?

Net::HTTP.start($xmlServerHostname) { |http|
       resp = http.get($xmlServerPath+"levels.xml")
       open("levels.xml", "w") { |file|
        file.write(resp.body)
       }
      }
+5  A: 

Before you do your http.get do an http.head which requests just the headers without downloading the body (i.e. the file contents) then check if the value of the Last Modified header has changed.

e.g.

resp = http.head(($xmlServerPath+"levels.xml")
last_modified = resp['last-modified']
if last_modified != previous_last_modified
  # file has changed
end
mikej
Can I do both http.head and http.get in the same HTTP.start block?
kramer
I've just tried it here and doing both in the same start block seems fine.
mikej
Ok, thanks a lot mikej!
kramer
+3  A: 

You can try to send the If-Modified-Since header with a correctly formatted date.

If the server supports it, it can answer just with a 304 Not Modified status (without any content) or the full content if the file has been modified.

Vincent Robert