Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 POSTing:

  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'.

like image 374
Tom Lehman Avatar asked Aug 09 '09 20:08

Tom Lehman


People also ask

How do I get parameters in GET request?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.

Can I pass parameters to a GET request?

In a GET request, you pass parameters as part of the query string.

CAN GET method have query parameters?

When the GET request method is used, if a client uses the HTTP protocol on a web server to request a certain resource, the client sends the server certain GET parameters through the requested URL. These parameters are pairs of names and their corresponding values, so-called name-value pairs.


2 Answers

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) 
like image 137
lime Avatar answered Oct 08 '22 19:10

lime


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) 
like image 40
Chris Moos Avatar answered Oct 08 '22 17:10

Chris Moos