Conditional GET 有两种,一种是etag, 另一种是last-modified。
关于这两种介绍,请移步:http://www.dbanotes.net/web/http_11_etag_lastmodified.html
我们分别来看一下这两种实现。
1。用ETag
require 'open-uri'
# 1st request -- save the ETag
etag = nil
open( "http://redhanded.hobix.com/index.xml" ) do |feed|
etag = feed.meta['etag']
end
# 2nd request -- only retrieve the file if it has changed
begin
open( "http://redhanded.hobix.com/index.xml",
"If-None-Match" => etag ) do |feed|
puts "File has changed: #{ feed.read.length } bytes read"
end
rescue OpenURI::HTTPError
puts "No file available or file has not changed."
end
2。用last-modified
require 'open-uri'
# 1st request -- save the modification time
mtime = nil
open( "http://redhanded.hobix.com/index.xml" ) do |feed|
mtime = feed.last_modified
end
# 2nd request -- only retrieve the file if it has changed
begin
open( "http://redhanded.hobix.com/index.xml",
"If-Modified-Since" => mtime.rfc2822 ) do |feed|
puts "File has changed: #{ feed.read.length } bytes read"
end
rescue OpenURI::HTTPError
puts "No file available or file has not changed."
end