简体   繁体   English

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

[英]How to consume Rest API with complex objects using Httparty and Ruby

I am trying to implement call this API method in Ruby https://zferral.com/api-docs/affiliate#aff-create-usage-example which expects this object: 我试图在Ruby中调用这个API方法https://zferral.com/api-docs/affiliate#aff-create-usage-example ,它需要这个对象:

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

Using a Httparty class, I call this: 使用Httparty类,我称之为:

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

Unfortunately, the API keeps sending me "Email is required". 不幸的是,API一直向我发送“需要电子邮件”。 I have tried to switch to json, I am changed :body with :query, etc... 我试图切换到json,我改变了:body with:query等...

Anybody could show me how to call the affiliate/create method correctly? 任何人都可以告诉我如何正确调用affiliate / create方法?

Thank you. 谢谢。

You're sending json, but posting it to create.xml --- in rails, this will auto-set the content type to be xml when you post to create.xml 您正在发送json,但是将其发布到create.xml ---在rails中,当您发布到create.xml时,这将自动将内容类型设置为xml

Try posting to /api/#{@apikey}/affiliate/create.json 尝试发布到/api/#{@apikey}/affiliate/create.json

If that doesn't work --- are you following the class design that HTTParty really likes? 如果这不起作用 - 您是否遵循HTTParty真正喜欢的课程设计? http://railstips.org/blog/archives/2008/07/29/it-s-an-httparty-and-everyone-is-invited/ http://railstips.org/blog/archives/2008/07/29/it-s-an-httparty-and-everyone-is-invited/

This is how I fixed my issue: 这就是我解决问题的方法:

    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM