Tom Lehman Tom Lehman - 3 months ago 15
Ruby Question

Parametrized get request in Ruby?

How do I make an HTTP

GET
request with parameters in Ruby?

It's easy to do when you're
POST
ing:

require 'net/http'
require 'uri'

HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
{ "q" => "ruby", "max" => "50" }


But I see no way of passing
GET
parameters as a hash using
'net/http'
.

Answer

Use the following method:

require 'net/http'
require 'cgi'

def http_get(domain,path,params)
    return Net::HTTP.get(domain, "#{path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&'))) if not params.nil?
    return Net::HTTP.get(domain, path)
end

params = {:q => "ruby", :max => 50}
print http_get("www.example.com", "/search.cgi", params)
Comments