Typhoeus 允许您使用 Ruby 构造传递 HTTP 参数。要生成与您帖子中的 URL 相似的 URL,您需要执行以下操作:
my_params = {
api_key: "XXXXXXXXXXXXXXXXXX",
objects: [
{ field1: 'My ObjectA2' },
{ field: 'ObjectB',
color: '1',
note: '98765' }],
ids: "foo, bar"
}
get_response = Typhoeus::Request.get("http://www.example.com/objects/add.php", params: my_params)
get_response.effective_url #> http://www.example.com/objects/add.php?api_key=XXXXXXXXXXXXXXXXXX&ids=foo%2C+bar&objects=%7B%3Afield1%3D%3E%22My+ObjectA2%22%7D&objects=%7B%3Afield%3D%3E%22ObjectB%22%2C+%3Acolor%3D%3E%221%22%2C+%3Anote%3D%3E%2298765%22%7D
但是,由于您的示例 URL 包含一个 JSON 对象,您正在使用的 API 似乎更有可能是在寻找 POST 请求。
post_response = Typhoeus::Request.post("http://www.example.com/objects/add.php", params: my_params)
post_response.effective_url #> http://www.example.com/objects/add.php
post_response.request.params #> {:api_key=>"XXXXXXXXXXXXXXXXXX", :objects=>[{:field1=>"My ObjectA2"}, {:field=>"ObjectB", :color=>"1", :note=>"98765"}], :ids=>"foo, bar"}
编辑:
如果 API 期待 GET 请求,目前通过 GET 请求传递序列化数据的最常见方法是在参数名称的末尾附加方括号:
http://www.example.com/objects/add.php?objects[]=something&objects[]=something%20else
但是,Typhoeus 默认不添加括号。Typhoeus 邮件列表上有一些讨论,提供了此决定背后的理由。幸运的是,您可以自己轻松地添加括号:
my_params = {
api_key: "XXXXXXXXXXXXXXXXXX",
:"objects[]" => [
{ field1: 'My ObjectA2' },
{ field: 'ObjectB',
color: '1',
note: '98765' }],
ids: "foo, bar"
}
get_response = Typhoeus::Request.get("http://www.example.com/objects/add.php", params: my_params)
get_response.effective_url #> http://www.example.com/objects/add.php?api_key=XXXXXXXXXXXXXXXXXX&ids=foo%2C+bar&objects%5B%5D=%7B%3Afield1%3D%3E%22My+ObjectA2%22%7D&objects%5B%5D=%7B%3Afield%3D%3E%22ObjectB%22%2C+%3Acolor%3D%3E%221%22%2C+%3Anote%3D%3E%2298765%22%7D