Parametrized get request in Ruby? Parametrized get request in Ruby? ruby ruby

Parametrized get request in Ruby?


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 URIuri.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)


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)endparams = {:q => "ruby", :max => 50}print http_get("www.example.com", "/search.cgi", params)


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 objectrequest = 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.