2015-06-05 55 views
1

我想將以下PHP腳本翻譯成Ruby以便與Web API進行通信。不幸的是,我似乎無法以正確的方式傳遞'收件人'數組,因爲它沒有被API正確解釋。 傳遞其他參數雖然工作正常。該問題僅在傳遞收件人數組時出現。Ruby使用Net :: HTTP.post_form發佈數組的HTTP請求

我該如何格式化這個Array或Hash?

PHP腳本:

<?php 
$params=array (
'username' => 'username', 
'password' => 'password', 
'listId' => 1, 
'recipients' => 
array (
0 => 
array (
1 => '[email protected]', 
3 => 'Max', 
), 
1 => 
array (
1 => '[email protected]', 
3 => 'Erika', 
), 
), 
'mode' => 'update_add', 
'advanced' => 
array (
'optoutSync' => 'global', 
'syncFieldId' => 1, 
'updateFieldId' => 3, 
), 
); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'https://login.mailingwork.de/webservice/webservice/json/importrecipients'); 
// curl_setopt($ch, CURLOPT_URL, 'http://ruby-doc.org'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); 
$result = json_decode(curl_exec($ch),true); 
print "errorcode:".$result['error']; 
print "message:".$result['message']; 
print "result:".print_r($result['result'],true); 
?> 

Ruby的腳本:

@params = { 
    'username' => 'username', 
    'password' => 'password', 
    'listId' => 1, 
    'recipients' => { 
     0 => { 1 => '[email protected]', 3 => 'Max' } 
     #1 => { 1 => '[email protected]', 3 => 'Erika2' } 
    }, 
'mode' => 'update_add', 

'advanced' => { 
    'optoutSync' => 'global', 
    'syncFieldId' => 1, 
    'updateFieldId' => 3 
} 
} 

Net::HTTP.post_form('https://login.mailingwork.de/webservice/webservice/json/importrecipients', @params) 

回答

0

收件人鍵可以做到像

recipients' => [ 
     0 => { 1 => '[email protected]', 3 => 'Max' }, 
     1 => { 1 => '[email protected]', 3 => 'Erika2' } 
    ], #rest of code goes here 

而且不要忘了用轉換爲JSON @params.to_json

相關問題