The following is the API call to a remote service that executes successfully when I use with HTTParty.
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
But when I try to make the same call using Faraday, I get this unknown error:
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
The error raised is:
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 l开发者_Go百科ine 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
It looks like you're using mislav's recent blog post about Faraday for a code sample. You'll notice that in his example, the code you used is only being used for a GET request, not a POST request. When he made a POST request earlier in the page, he set a specific Faraday::Request
type.
Based on the discussion at github, moment requires that you post JSON data, so you need to use this:
builder.use Faraday::Request::JSON
精彩评论