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\'
Since version 1.9.2 (I think) you can actually pass the parameters as a hash to the URI::encode_www_form method like this:
require 'uri'
uri = URI.parse('http://www.example.com/search.cgi')
params = { :q => "ruby", :max => "50" }
# Add params to URI
uri.query = URI.encode_www_form( params )
and then fetch the result, depending on your preference
require 'open-uri'
puts uri.open.read
or
require 'net/http'
puts Net::HTTP.get(uri)
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
Use Excon:
conn = Excon.new('http://www.example.com/search.cgi')
conn.get(:query => { "q" => "ruby", "max" => "50" })
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.
This is the easiest way to do it
require 'net/http' require 'uri'
@siteurl = "http://www.google.de/search/#{@yourquery}"
define your query
@yourquery = "whatever"
uri = URI.parse( "@siteurl" );
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body )
response = http.request(request)
puts response.body
Might not be perfect but at least you get the idea.
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