12
A
回答
6
我假定您了解Net::HTTP documentation page上的示例,但是您不知道如何将参数传递给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"
14
我知道这个职位是旧的,但对于那些通过谷歌带到这里的缘故,有编码的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 => "[email protected]"})
=> #<Net::HTTPCreated 201 Created readbody=true>
相关问题
- 1. 红宝石HTTP POST参数
- 2. 红宝石参数
- 3. 如何获得红宝石2.0模块#prepend在红宝石1.8?
- 4. 红宝石ajax请求与参数
- 5. 红宝石:参数与变量
- 6. 产卵与红宝石参数
- 7. 获取参数里面的红宝石
- 8. 与红宝石
- 9. 与红宝石
- 10. 与红宝石
- 11. 与红宝石
- 12. 与红宝石
- 13. 红宝石方法参数
- 14. 红宝石参数错误
- 15. 红宝石:在块参数
- 16. 红宝石 - 方法参数
- 17. 红宝石instance_exec /带参数
- 18. “_”红宝石的参数块
- 19. 提取红宝石参数
- 20. 得到红宝石
- 21. 红宝石参考
- 22. 红宝石 - 问题与HTTP邮政
- 23. 可选参数/参数在红宝石
- 24. 红宝石`each_with_object`与指数
- 25. 红宝石网/ http难点
- 26. 红宝石HTTP请求
- 27. 红宝石:HTTP PUT方法
- 28. HTTP请求红宝石
- 29. 使用网:: HTTP红宝石
- 30. REST与红宝石?
你可以发布你已经有的东西吗? –
你想用这个请求做什么?你想得到回应吗? –
你看过'net/http'文件吗?如果是,那还不清楚? –