如何在ruby的net / http 1.9.3-p194中发送带有查询参数的GET?

时间:2014-03-19 21:24:05

标签: ruby http net-http

我试图在ruby 1.9.3-p194中向http://www.hello.com/sup?a=b发送GET(由于遗留代码无法更新版本)

uri = URI.parse("http://www.hello.com/sup?a=b")
uri.query = "a=b"

req = Net::HTTP::Get.new(uri)
response = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
case response
  when Net::HTTPSuccess     then response
  else
     puts "Error"
end

我实际上使用的是ruby 1.9.3-p194,但我收到了这个错误:

/Users/hithere/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:1860:in `initialize': undefined method `empty?' for #<URI::HTTP:0x007f938d9051c8> (NoMethodError)
from /Users/hithere/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/http.rb:2093:in `initialize'
from send_to_hg_given_place_id.rb:101:in `new'
from send_to_hg_given_place_id.rb:101:in `block in fetch'
from /Users/hithere/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/timeout.rb:68:in `timeout'
from send_to_hg_given_place_id.rb:100:in `fetch'
from send_to_hg_given_place_id.rb:141:in `block in <main>'
from send_to_hg_given_place_id.rb:133:in `each'
from send_to_hg_given_place_id.rb:133:in `<main>'

出于某种原因,它试图使用http.rb 1.9.1,并且1.9.1要求#new中的参数为String而不是URI。我想修复它以便它使用1.9.3,或者获得适用于1.9.1的解决方案http.rb

2 个答案:

答案 0 :(得分:0)

而不是

uri = URI.parse(http://www.hello.com/sup?a=b)

它将是

uri = URI.parse("http://www.hello.com/sup?a=b")

答案 1 :(得分:0)

您可以Net::HTTP参考Net::HTTP::Get.new。您需要在uri.request_uri

中传递一个字符串

以下是一个示例(注意uri = URI('http://example.com/some_path?query=string') Net::HTTP.start(uri.host, uri.port) do |http| request = Net::HTTP::Get.new uri.request_uri response = http.request request # Net::HTTPResponse object end ):

{{1}}

您可以附加到网址的GET参数。只需注意URL编码即可。例如,见examples