Skip to content

Instantly share code, notes, and snippets.

@isaksky
Created February 18, 2012 21:51
Show Gist options
  • Save isaksky/1861104 to your computer and use it in GitHub Desktop.
Save isaksky/1861104 to your computer and use it in GitHub Desktop.
get_response_following_redirects
def self.get_response_following_redirects orig_uri, requests_limit = 15
raise "Input must be an absolute URI." unless orig_uri.is_a?(URI::Generic) && orig_uri.absolute?
uri = orig_uri
requests_made = 0
while requests_made <= requests_limit
response = Net::HTTP.get_response uri
requests_made += 1
case response
when Net::HTTPSuccess
return response
when Net::HTTPRedirection
redirect_url = response.header['location']
unless redirect_url.is_a?(String) && !redirect_url.empty?
raise "Redirect Error, no redirect location specified."
end
temp_uri = URI(redirect_url)
if temp_uri.relative?
uri = uri.merge temp_uri #make URI absolute
else
uri = temp_uri
end
else
raise "Don't know what to do with this response: #{response.inspect}"
end
end
raise "Too many redirects (#{requests_limit}) error"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment