微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 如何使用HTTParty实现此POST请求?

我无法使用 Ruby的HTTParty库向API端点发送POST请求.我正在与之互动的API是 Gittip API,其端点需要身份验证.我已经能够使用HTTParty成功地进行身份验证的GET请求.

您可以在示例代码中看到:

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"
# I have included real credentials since the above is merely a test account.

HTTParty.get("https://www.gittip.com/#{user}/tips.json",{ :basic_auth => { :username => api_key } })

该请求的作用并按预期返回以下内容

[
  {
    "amount" => "1.00","platform" => "gittip","username" => "whit537"
  },{
    "amount" => "0.25","username" => "JohnKellyFerguson"
  }
]

但是,我无法使用HTTParty成功发送POST请求. Gittip API描述了使用curl进行POST请求,如下所示:

curl https://www.gittip.com/foobar/tips.json \
  -u API_KEY: \
  -X POST \
  -d'[{"username":"bazbuz","platform":"gittip","amount": "1.00"}]' \
  -H"Content-Type: application/json"

我尝试(不成功)使用HTTParty构造我的代码,如下所示:

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"

HTTParty.post("https://www.gittip.com/#{user}/tips.json",{ 
                :body => [ { "amount" => "0.25","username" => "whit537" } ],:basic_auth => { :username => api_key },:headers => { 'Content-Type' => 'application/json' }
               })

一个参数是url,第二个参数是一个选项哈希.当我运行上面的代码,我得到以下错误

NoMethodError: undefined method `bytesize' for [{"amount"=>"0.25","platform"=>"gittip","username"=>"whit537"}]:Array
  from /Users/John/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http/generic_request.rb:179:in `send_request_with_body'

我已经尝试了各种其他的结构化API调用的组合,但是无法弄清楚如何使其工作.这是另一个这样的例子,我不会将数组用作body的一部分,并将内容转换为_json.

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"

HTTParty.post("https://www.gittip.com/#{user}/tips.json",{
            :body => { "amount" => "0.25","username" => "whit537" }.to_json,:headers => { 'Content-Type' => 'application/json' }
           })

哪个返回以下(一个500错误):

<html>
  <head>
    <title>500 Internal Server Error</title>
  </head>
  <body>\n        Internal server error,program!\n        <pre></pre>  
  </body>
</html>

我不是很熟悉卷曲,所以我不知道我是否错误地将东西翻译成HTTParty.

任何帮助将不胜感激.谢谢.

解决方法

只是一个猜测,但是看起来你希望在JSON中传递散列.

尝试用以下代替:body声明:

:body => [{ "amount" => "0.25","username" => "whit537" }].to_json

编辑:
我建议使用to_json序列化程序,但是将其放在哈希而不是数组之后,将其放在一起,并将其完全删除.该示例使用多个记录,因此阵列是必需的.

看着this thread后,看起来Gittip对于接受标题很挑剔.

:headers => { 'Content-Type' => 'application/json','Accept' => 'application/json'}

所以,完整的建议是:

HTTParty.post("https://www.gittip.com/#{user}/tips.json",{ 
    :body => [ { "amount" => "0.25","username" => "whit537" } ].to_json,:headers => { 'Content-Type' => 'application/json','Accept' => 'application/json'}
  })

原文地址:https://www.jb51.cc/ruby/271911.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐