Parametrized get request in Ruby?

2020-01-30 04:24发布

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

7条回答
叼着烟拽天下
2楼-- · 2020-01-30 04:59

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)
查看更多
登录 后发表回答