使用Ruby gem Typhoeus进行Api请求

时间:2013-09-26 16:02:21

标签: ruby api httparty typhoeus

以下请求有什么问题?

request = Typhoeus::Request.new("http://fluidsurveys.com/api/v2/groups",
                                    method: :get,
                                    userpwd: "test_user:test_password",
                                    headers: { 'ContentType' => "application/json"})
response = request.body
puts response

这会返回undefined method body for #<Typhoeus::Request:0x007f8e50d3b1d0> (NoMethodError)

以下请求适用于httparty

call= "/api/v2/groups/"
auth = {:username => "test_user", :password => "test_password"}
url = HTTParty.get("http://fluidsurveys.com/api/v2/groups",
                   :basic_auth => auth,
                   :headers => { 'ContentType' => 'application/json' } )
response = url.body
puts response

编辑:

我试过了:

response = request.response
puts response.body
没有运气。我收到了这个:undefined method body for nil:NilClass (NoMethodError)

2 个答案:

答案 0 :(得分:6)

来自https://github.com/typhoeus/typhoeus

您需要在响应正文可用之前执行get操作。

编辑:这是一个可操作的解决方案。它不使用您的网站,我甚至无法手动访问。但是,这会返回响应代码200和response_body。在我的调试器中运行它显示了完整的响应,您可以使用“puts response.inspect”查看。

class TyphoeusTry
  require 'typhoeus'
  request = Typhoeus::Request.new("http://www.google.com",
                                  method: :get,
                                  userpwd: "test_user:test_password",
                                  headers: { ContentType: "application/json"})
  response = request.run
  puts response.response_body
end

答案 1 :(得分:0)

问题是您实际上没有执行您的请求。以下代码应该可以使用。

request = Typhoeus::Request.new("http://fluidsurveys.com/api/v2/groups",
                                method: :get,
                                userpwd: "test_user:test_password",
                                headers: { 'ContentType' => "application/json"})

request.run
response = request.response
response_code = response.code
response_body = response.body