【问题标题】:Ruby posting a HTTP request with arrays using Net::HTTP.post_formRuby 使用 Net::HTTP.post_form 发布带有数组的 HTTP 请求
【发布时间】:2015-06-05 10:00:15
【问题描述】:

我正在尝试将以下 PHP 脚本翻译成 Ruby,以便与 Web API 进行通信。不幸的是,我似乎无法以正确的方式传递“收件人”数组,因为 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)

【问题讨论】:

    标签: php arrays ruby http-request


    【解决方案1】:

    收件人键可以像这样完成

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

    别忘了用@params.to_json转成json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 2012-12-15
      • 2023-03-08
      • 2016-01-12
      • 1970-01-01
      相关资源
      最近更新 更多