我知道这篇文章已经很旧了,但是为了那些由 google 带到这里的人,有一种更简单的方法可以以 URL 安全的方式对参数进行编码。我不知道为什么我没有在其他地方看到这个方法,因为该方法记录在 Net::HTTP 页面上。我也看到 Arsen7 描述的方法作为其他几个问题的公认答案。
中提到的网络::HTTP http://www.ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html文档是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 => "[email protected] /cdn-cgi/l/email-protection"})
=> #<Net::HTTPCreated 201 Created readbody=true>