Ruby中的参数化get请求?

时间:2009-08-09 20:33:50

标签: ruby-on-rails ruby http get

如何使用Ruby中的参数创建HTTP GET请求?

当您POST时,这很容易做到:

  require 'net/http'
  require 'uri'

  HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
                 { "q" => "ruby", "max" => "50" }

但我认为无法使用GET'net/http'参数作为哈希传递。

7 个答案:

答案 0 :(得分:73)

从版本1.9.2(我认为)开始,您可以将参数作为哈希传递给URI::encode_www_form方法,如下所示:

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 )

然后根据您的偏好获取结果

require 'open-uri'

puts uri.open.read

require 'net/http'

puts Net::HTTP.get(uri)

答案 1 :(得分:29)

使用以下方法:

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)

答案 2 :(得分:18)

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 object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body ) 

response = http.request(request)
puts response.body

我希望它在没有第二个实例化的情况下工作,因为它将是第一个请求对象或http对象的工作,但它对我有用。

答案 3 :(得分:5)

Net::HTTP.get_print 'localhost', '/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15'

uri = URI.parse("http://localhost")
req = Net::HTTP::Get.new("/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15")

http = Net::HTTP.new(uri.host, uri.port)

response = http.start do |http| 
  http.request(req)
end

答案 4 :(得分:4)

使用Excon

conn = Excon.new('http://www.example.com/search.cgi')
conn.get(:query => { "q" => "ruby", "max" => "50" })

答案 5 :(得分:2)

新的堆栈溢出,我想我无法评论,但@ chris.moose在他的函数def中缺少双引号。第5行应该是:

return Net::HTTP.get(domain, "#{path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.reverse.join('&'))) if not params.nil?

或者这里是为复制/粘贴重新定义的全部内容

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)}" }.reverse.join('&'))) if not params.nil?
    return Net::HTTP.get(domain, path)
end

< 3 -Mike

答案 6 :(得分:0)

This is the easiest way to do it

 require 'net/http' require 'uri'
 @siteurl = "http://www.google.de/search/#{@yourquery}"
define your query
 @yourquery = "whatever"



uri = URI.parse( "@siteurl" );
http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Get.new(uri.path) 

# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body ) 

response = http.request(request)
puts response.body

可能不完美,但至少你明白了。