Ruby HTTP得到params

如何通过ruby发送带参数的HTTP GET请求?

我尝试了很多例子,但所有这些都失败了。

我知道这篇文章很老但是为了谷歌带来的那些,有一种更简单的方法来以URL安全的方式对参数进行编码。 我不知道为什么我没有在其他地方看到这个,因为该方法记录在Net :: HTTP页面上。 我已经看到Arsen7描述的方法也是其他几个问题的公认答案。

Net :: HTTP文档中提到的是URI.encode_www_form(params)

 # Lets say we have a path and params that look like this: path = "/search" params = {q: => "answer"} # Example 1: Replacing the #path_with_params method from Arsen7 def path_with_params(path, params) encoded_params = URI.encode_www_form(params) [path, encoded_params].join("?") end # Example 2: A shortcut for the entire example by Arsen7 uri = URI.parse("http://localhost.com" + path) uri.query = URI.encode_www_form(params) response = Net::HTTP.get_response(uri) 

您选择哪个示例在很大程度上取决于您的用例。 在我当前的项目中,我使用的方法类似于Arsen7推荐的方法以及更简单的#path_with_params方法,并且没有块格式。

 # Simplified example implementation without response # decoding or error handling. require "net/http" require "uri" class Connection VERB_MAP = { :get => Net::HTTP::Get, :post => Net::HTTP::Post, :put => Net::HTTP::Put, :delete => Net::HTTP::Delete } API_ENDPOINT = "http://dev.random.com" attr_reader :http def initialize(endpoint = API_ENDPOINT) uri = URI.parse(endpoint) @http = Net::HTTP.new(uri.host, uri.port) end def request(method, path, params) case method when :get full_path = path_with_params(path, params) request = VERB_MAP[method].new(full_path) else request = VERB_MAP[method].new(path) request.set_form_data(params) end http.request(request) end private def path_with_params(path, params) encoded_params = URI.encode_www_form(params) [path, encoded_params].join("?") end end con = Connection.new con.request(:post, "/account", {:email => "test@test.com"}) => # 

我假设您了解Net :: HTTP文档页面上的示例,但您不知道如何将参数传递给GET请求。

您只需将参数附加到请求的地址,就像在浏览器中键入此类地址一样:

 require 'net/http' res = Net::HTTP.start('localhost', 3000) do |http| http.get('/users?id=1') end puts res.body 

如果您需要一些通用的方法来从哈希构建参数字符串,您可以创建一个这样的帮助器:

 require 'cgi' def path_with_params(page, params) return page if params.empty? page + "?" + params.map {|k,v| CGI.escape(k.to_s)+'='+CGI.escape(v.to_s) }.join("&") end path_with_params("/users", :id => 1, :name => "John&Sons") # => "/users?name=John%26Sons&id=1"