【问题标题】:Api Requests with Ruby gem TyphoeusRuby gem Typhoeus 的 Api 请求
【发布时间】:2013-09-26 16:02:20
【问题描述】:

以下请求有什么问题?

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)

【问题讨论】:

    标签: ruby api httparty typhoeus


    【解决方案1】:

    来自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
    

    【讨论】:

    • 拍头...好吧,当然,在你得到身体之前你必须得到回应。是否有任何关于 request.response 的日志消息?我希望响应方法返回 HTTP 错误的哈希值或整数值,而不是 nil。另外,我会做一些研究,然后会回来......
    • 我没有看到任何其他错误消息。正在发生的事情是request.response 回来为零,没有返回任何信息。我真的找不到http错误代码。使用 httparty 我会使用 puts url.code 来获取代码,但我似乎无法弄清楚如何使用 typhoeus 来获取该值。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2016-06-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      相关资源
      最近更新 更多