为什么与HTTParty一起使用的api调用不适用于法拉第?

时间:2011-07-16 11:47:19

标签: ruby-on-rails ruby-on-rails-3 rubygems

以下是对我使用HTTParty时成功执行的远程服务的API调用。

require 'httparty'

class TheAPI
  include HTTParty
  base_uri 'https://someapp.com'
  # headers  "Content-Type" => "application/json"

  def self.create_job
    post( '/jobs.json', :query => {:apikey => "kOrROwbVPNC34VZYhbET", :job => {:method => "PUT", :at => '2012-01-31T18:36:21', :uri => "http://kasko.com"}})
  end
end

puts TheAPI.create_job

但是当我尝试使用法拉第进行相同的调用时,我得到了这个未知的错误:

require 'faraday_stack'

conn = Faraday.new 'https://someapp.com', ssl: {verify: false} do |builder|
  builder.use   FaradayStack::ResponseJSON,     content_type: 'application/json'
  builder.use   Faraday::Response::Logger#,      Logger.new('faraday.log')
  # builder.use FaradayStack::FollowRedirects,  limit: 3
  builder.use Faraday::Response::RaiseError   # raise exceptions on 40x, 50x responses
  builder.use   Faraday::Adapter::NetHttp
end

# conn.headers[:user_agent] = 'MyLib v1.2'

resp = conn.post "jobs.json", {:apikey => "kOrROwbVPNC34VZYhbET", :job => {:method => "PUT", :at => '2012-01-31T18:36:21', :uri => "http://kasko.com"}}
puts resp

引发的错误是:

NoMethodError: undefined method ‘bytesize’ for #<Hash:0x000001011ab8f8>

method send_request_with_body   in http.rb at line 1735
method exec in http.rb at line 1724
method transport_request    in http.rb at line 1189
method request  in http.rb at line 1177
method block in request in http.rb at line 1170
method start    in http.rb at line 627
method request  in http.rb at line 1168
method call in net_http.rb at line 51
method call in response.rb at line 8
method call in response.rb at line 8
method call in logger.rb at line 20
method call in response.rb at line 8
method run_request  in connection.rb at line 203
method post in connection.rb at line 90
method <main>   in test.rb at line 33

1 个答案:

答案 0 :(得分:2)

您似乎正在使用mislav's recent blog post about Faraday代码示例。您会注意到,在他的示例中,您使用的代码仅用于GET请求,而不是POST请求。当他在页面的前面发出POST请求时,他设置了一个特定的Faraday::Request类型。

根据github的讨论,moment要求您发布JSON数据,因此您需要使用此功能:

builder.use Faraday::Request::JSON