2013-09-26 93 views
2

以下請求有什麼問題?Api請求與紅寶石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)

回答

6

https://github.com/typhoeus/typhoeus

您需要的響應體可用前做搞定。

編輯:這是一個可操作的解決方案。它不使用您的網站,我甚至無法手動訪問。但是,這會返回響應代碼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 
+0

該方法仍然返回錯誤。 – Luigi

+0

它在上面的編輯中。 – Luigi

+0

頭巴掌...好的,所以你必須得到一個響應,然後才能得到身體,當然。有沒有關於request.response的日誌消息?我期望響應方法返回一個哈希或HTTP錯誤的整數值,而不是零。此外,我要做一些研究,並會回來... –

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