代码之家  ›  专栏  ›  技术社区  ›  Aymeric

如何使用Httparty和Ruby使用复杂对象的Rest API

  •  1
  • Aymeric  · 技术社区  · 16 年前

    https://zferral.com/api-docs/affiliate#aff-create-usage-example 期望此对象:

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

    使用Httparty类,我称之为:

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

    不幸的是,API一直在向我发送“Email is required”。我试图切换到json,我被改变了:body with:query,等等。。。

    谢谢您。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Jesse Wolgamott    16 年前

    您发送的是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
  •  2
  •   Aymeric    16 年前

        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)
    
    推荐文章