【问题标题】:post HTTP query via HTTParty通过 HTTParty 发布 HTTP 查询
【发布时间】:2018-10-03 22:20:22
【问题描述】:

我想使用 mailerlite API 将订阅者添加到列表中

这是 APIdoc 所说的生成请求的内容

$subscriber = array(
    'email' => 'foo@bar.com',
    'name' => 'foo',
    'fields' => array( 
       array( 'name' => 'country', 'value' => "usa" )
    )
);
$subscriber = $ML_Subscribers->setId( LIST_ID )->add( $subscriber );

它会生成一个这样的查询字符串

email=foo%40bar.com&name=foo&fields%5B0%5D%5Bname%5D=country&fields%5B0%5D%5Bvalue%5D=usa

并将其发送到 mailerlite 服务器 我的问题是如何通过 ruby​​ HTTParty gem 或 rails 方法生成字符串

【问题讨论】:

    标签: ruby-on-rails ruby httprequest httparty


    【解决方案1】:

    ActiveSupport猴子补丁对象添加#to_query方法,你可以在你的哈希上调用它来获取查询字符串:

    subscriber = {
      'email' => 'foo@bar.com',
      'name' => 'foo',
      'fields' => {
        'name' => 'country', 
        'value' => "usa" 
      }
    }
    
    subscriber.to_query
    "email=foo%40bar.com&fields%5Bname%5D=country&fields%5Bvalue%5D=usa&name=foo"
    

    【讨论】:

    【解决方案2】:

    您可以为 https://github.com/jpalumickas/mailerlite-ruby 使用 MailerLite Ruby gem

    client = MailerLite::Client.new(api_key: 'my-secret-api-key')
    client.create_subscriber(email: 'john@example.com', name: 'John Smith')
    

    【讨论】:

      【解决方案3】:

      要生成与 php 代码完全相同的结果,您应该使用这个 gem https://rubygems.org/gems/php_http_build_query

      使用示例

      puts PHP.http_build_query({"a"=>"b","c"=>"d","e"=>[{"hello"=>"world","bah"=>"black"},{"hello"=>"world","bah"=>"black"}]})
      
      #a=b&c=d&e%5B0%5D%5Bbah%5D=black&e%5B0%5D%5Bhello%5D=world&e%5B1%5D%5Bbah%5D=black&e%5B1%5D%5Bhello%5D=world
      

      【讨论】:

        猜你喜欢
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 2015-09-02
        • 1970-01-01
        • 2014-12-28
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多