views:

2161

answers:

4

How do I make an HTTP GET request with parameters in Ruby?

It's easy to do when you're POSTing:

  require 'net/http'
  require 'uri'

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

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

+6  A: 

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)
chris.moos
Surely there must be a more abstract way to do this, no?
Horace Loeb
I don't think there is in Net::HTTP...but you could just write a method that takes 3 parameters, the domain, path, and parameters, and returns the result, so you don't have to run the collect manually each time.
chris.moos
@Horace LoebThere is no point abstracting this. It's so simple an abstraction isn't going to save you any code.
Henry
What's the point of the `reverse` here? Given that hashes are orderless (usually), and the order of the variables on the query doesn't matter.
Squeegy
+2  A: 
require 'net/http' require 'uri'

uri = URI.parse( "http://www.google.de/search" ); params = {'q'=>'cheese'}

http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Get.new(uri.path) 
request.set_form_data( params )

# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body ) 

response = http.request(request)
puts response.body

I would expect it to work without the second instantiation as it would be the first request-objects or the http-object's job but it worked for me this way.

marc
A: 

Net::HTTP.get_print 'localhost', '/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15'

or

uri = URI.parse("http://localhost") req = Net::HTTP::Get.new("/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15")

http = Net::HTTP.new(uri.host, uri.port)

response = http.start do |http| http.request(req) end

mike
A: 

new to stack overflow and I guess I can't comment, but @chris.moose is missing double quotes in his function def. line 5 should be:

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

or here's the whole thing redefined for copy/pasting

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)}" }.reverse.join('&'))) if not params.nil?
    return Net::HTTP.get(domain, path)
end

<3 -mike

Michael Glass