【问题标题】:How to consume Rest API with complex objects using Httparty and Ruby如何使用 Httparty 和 Ruby 使用带有复杂对象的 Rest API
【发布时间】:2010-08-25 09:45:39
【问题描述】:

我正在尝试在 Ruby https://zferral.com/api-docs/affiliate#aff-create-usage-example 中调用这个 API 方法,它需要这个对象:

{  "affiliate" : {
    "email"           : "john@example.com",
    "send_user_email" : "1" }}

使用 Httparty 类,我称之为:

result = self.class.post("/api/#{@apikey}/affiliate/create.xml", :body => {:affiliate => {:email => email}})

很遗憾,API 不断向我发送“需要电子邮件”。我试图切换到 json,我改变了 :body 和 :query 等...

谁能告诉我如何正确调用affiliate/create 方法?

谢谢。

【问题讨论】:

    标签: ruby-on-rails json httparty


    【解决方案1】:

    您正在发送 json,但将其发布到 create.xml --- 在 rails 中,这将在您发布到 create.xml 时自动将内容类型设置为 xml

    尝试发帖到/api/#{@apikey}/affiliate/create.json

    如果这不起作用 --- 你是否遵循 HTTParty 真正喜欢的类设计? http://railstips.org/blog/archives/2008/07/29/it-s-an-httparty-and-everyone-is-invited/

    【讨论】:

      【解决方案2】:

      这就是我解决问题的方法:

          url = URI.parse('https://xxxx.zferral.com/api/xxx/affiliate/create.xml')
          http = Net::HTTP.new(url.host, url.port)
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
          request = Net::HTTP::Post.new(url.path)
          request.body = "<?xml version='1.0' encoding='UTF-8'?><affiliate><email>#{email}</email><send_user_email>0</send_user_email></affiliate>"
          request.content_type = 'text/xml'
          response = http.request(request)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        • 2012-05-28
        • 1970-01-01
        • 2011-01-26
        相关资源
        最近更新 更多