Skip to content

Instantly share code, notes, and snippets.

@koseki
Created September 3, 2009 08:31
Show Gist options
  • Save koseki/180191 to your computer and use it in GitHub Desktop.
Save koseki/180191 to your computer and use it in GitHub Desktop.
Simple HTTP request
require 'net/http'
require 'uri'
# Simple HTTP request
#
# See also:
# http://addressable.rubyforge.org/
# http://dev.ctor.org/http-access2
#
def http_request(method, uri, query_hash = {}, user = nil, pass = nil)
uri = URI.parse(uri) if uri.is_a? String
method = method.to_s.strip.downcase
query_string = (query_hash||{}).map{|k,v|
URI.encode(k.to_s) + "=" + URI.encode(v.to_s)
}.join("&")
if method == "post"
args = [Net::HTTP::Post.new(uri.path), query_string]
else
args = [Net::HTTP::Get.new(uri.path + (query_string.empty? ? "" : "?#{query_string}"))]
end
args[0].basic_auth(user, pass) if user
Net::HTTP.start(uri.host, uri.port) do |http|
return http.request(*args)
end
end
# Simple HTTP request with redirection.
def http_request2(method, uri, query_hash = {}, user = nil, pass = nil, max_redirection = 3)
response = http_request(method, uri, query_hash, user, pass)
case response
when Net::HTTPSuccess
return response
when Net::HTTPRedirection
raise ArgumentError, 'Too many redirection.' if max_redirection <= 0
return http_request2(method, response["location"], query_hash, user, pass, max_redirection - 1)
else
response.error!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment