百頭巨怪允許您使用Ruby構建通過HTTP參數。爲了產生一個類似於在您的文章的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默認不會添加括號。有一些討論on the Typhoeus mailing list提供了這個決定背後的推理。幸運的是,您可以輕鬆地自行添加括號:
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
是的,一些實際的代碼會有所幫助。此外,請檢查您的Web服務器日誌,以確切瞭解您的請求在兩種情況下都已轉換爲何種格式(Chrome與Ruby)。 – theglauber 2012-01-09 20:37:51
@Krule:是什麼讓它失效? – 2012-01-11 01:11:04