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'
.
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.
In a GET request, you pass parameters as part of the query string.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With