Ruby使用Net :: HTTP.post_form向数组发布HTTP请求

时间:2015-06-05 10:00:16

标签: php arrays ruby http-request

我正在尝试将以下PHP脚本翻译成Ruby,以便与Web API进行通信。不幸的是,我似乎无法以正确的方式传递'recipients'数组,因为API没有正确解释它。 传递其他参数工作正常。只有在传递收件人数组时才会出现此问题。

我应该如何格式化此数组或哈希?

PHP脚本:

<?php
$params=array (
'username' => 'username',
'password' => 'password',
'listId' => 1,
'recipients' =>
array (
0 =>
array (
1 => 'max@mustermann.de',
3 => 'Max',
),
1 =>
array (
1 => 'erika@mustermann.de',
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 => 'max@mustermann.de', 3 => 'Max' }
         #1 => { 1 => 'erika@mustermann.de', 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)

1 个答案:

答案 0 :(得分:0)

收件人密钥可以像

一样完成
recipients' => [
         0 => { 1 => 'max@mustermann.de', 3 => 'Max' },
         1 => { 1 => 'erika@mustermann.de', 3 => 'Erika2' }
    ], #rest of code goes here

另请不要忘记使用@params.to_json

转换为json