def handle_response(uri, resp, opts, &block)
if Net::HTTPRedirection === resp && opts[:max_redir] >= 0
if resp.key?('location')
raise 'Too many redirections' if opts[:max_redir] <= 0
yield resp if opts[:yield] == :all && block_given?
loc = resp['location']
new_loc = URI.join(uri.to_s, loc) rescue URI.parse(loc)
new_opts = opts.dup
new_opts[:max_redir] -= 1
case opts[:method].to_s.downcase.intern
when :post, "net::http::post""net::http::post"
new_opts[:method] = :get
end
if resp['set-cookie']
debug "setting cookie #{resp['set-cookie']}"
new_opts[:headers] ||= Hash.new
new_opts[:headers]['Cookie'] = resp['set-cookie']
end
debug "following the redirect to #{new_loc}"
return get_response(new_loc, new_opts, &block)
else
warning ":| redirect w/o location?"
end
end
class << resp
undef_method :body
alias :body :cooked_body
end
unless resp['content-type']
debug "No content type, guessing"
resp['content-type'] =
case resp['x-rbot-location']
when /.html?$/i
'text/html'
when /.xml$/i
'application/xml'
when /.xhtml$/i
'application/xml+xhtml'
when /.(gif|png|jpe?g|jp2|tiff?)$/i
"image/#{$1.sub(/^jpg$/,'jpeg').sub(/^tif$/,'tiff')}"
else
'application/octetstream'
end
end
if block_given?
yield(resp)
else
resp.raw_body
end
return resp
end