在Ruby中的参数化获取请求?
我如何使用Ruby中的参数进行HTTP GET
请求?
当你在POST
时很容易做到:
require 'net/http' require 'uri' HTTP.post_form URI.parse('http://www.example.com/search.cgi'), { "q" => "ruby", "max" => "50" }
但是我没有看到使用'net/http'
作为散列传递GET
参数的方法。
使用以下方法:
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)
从版本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)
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对象的工作,但它对我来说是这样工作的。
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
使用Excon :
conn = Excon.new('http://www.example.com/search.cgi') conn.get(:query => { "q" => "ruby", "max" => "50" })
新的堆栈溢出,我想我不能评论,但@ chris.moose在他的函数def缺less双引号。 第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
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
可能不完美,但至less你明白了。