简体   繁体   English

Ruby Net :: Http Api,使用GET / POST发送多个参数

[英]Ruby Net::Http Api , Sending Multiple Parameters with GET/POST

I try to create a generic method to send GET/POST data with parameters using Ruby using NET:HTTP api ( https://apidock.com/ruby/Net/HTTP ). 我尝试创建一个通用方法来使用NET:HTTP api( https://apidock.com/ruby/Net/HTTP )使用Ruby发送带有参数的GET / POST数据。 Therefore, the number of parameters is not fixed. 因此,参数的数量不是固定的。 I know how to add a form data, as it is explained at : Get HTTP request in Ruby , I use; 我知道如何添加表单数据,如以下所述:我在Ruby中获取HTTP请求

uri = URI('http://www.example.com/todo.cgi') 
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

However it works when I know how many parameters I will have. 但是,当我知道我将拥有多少个参数时,它就可以工作。 I tried this but could not find how to add data instead of replacing. 我试过了,但找不到如何添加数据而不是替换数据。

parameter_list.each_with_index do |param,index|
req.set_form_data(param.to_s => value_list[index])
end

How can I make "For each parameter in my parameter list, add form data"? 如何制作“对于我的参数列表中的每个参数,添加表单数据”?

You can create your own hash by joining parameter_list with value_list and converting it to hash, and then pass it as the form data, like: 您可以通过将parameter_listvalue_list并将其转换为hash,然后将其作为表单数据传递来创建自己的哈希,例如:

parameter_list = %w[from to foo]
value_list = %w[2005-01-01 2005-03-31 bar]

form_data = parameter_list.zip(value_list).to_h

p form_data
# {"from"=>"2005-01-01", "to"=>"2005-03-31", "foo"=>"bar"}
req.set_form_data form_data

Note a constraint is both arrays must have the same size. 注意一个约束是两个数组必须具有相同的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM