2010-08-23 63 views
13

如何在做一個帖子後,在一個單獨的腳本中使用httparty從一個rails項目獲取響應url或id?ruby​​ httparty獲得帖子後的回覆url或id

Ruby腳本:

HTTParty.post('http://localhost:3000/change_logs', parameters) 

response.body和所有其他的人不顯示的URL和響應ID

回答

-1

這個工作對我來說,可能有一個更好的辦法,雖然這樣做..

get_change_log_id = HTTParty.post('http://localhost:3000/change_logs.xml', parameters).to_a 

get_change_log_id.each do |r| 
    r.each do |sub| 
    sub2 = sub.to_a 
     sub2.each do |s| 
     if s.index "id" 
      @change_log_id = s.to_s.sub(/[i]/, '').sub(/[d]/, '') 
     end 
     end 
    end 
end 
+0

是有一個更簡單的方法: 結果= HTTPa rty.post('http:// localhost:3000/change_logs.xml',參數) change_log_id = results.parsed_response [「change_log」]。values_at(「id」) – nictrix 2010-08-31 05:58:40

3

不幸的是,這些信息沒有保存的HTTParty。當它遇到重定向時,它將遵循重定向並返回該請求的結果。它不會保存原始請求中的任何信息。好消息是,這樣的行爲是(通常)可預測的。 Web應用程序通常在向URL發送請求後重定向到相同的東西。

但是,如果你真的想這樣做,你將不得不使用Ruby附帶的net/http庫。雖然沒有比HTTParty更難,所以沒有太多的工作。

+2

感謝您的答覆,這是有道理的 - 但我沒有想出一個辦法做到這一點..這是一個有點古怪,但 – nictrix 2010-08-23 15:25:07

26

兩年後,我發現了一種從上responserequest屬性訪問最後一個URI:

url  = "http://example.com/redirects/to/www" 
response = HTTParty.get(url) 
response.request.last_uri.to_s 
# => "http://www.example.com" 
+3

如果你想要做到這一點,最終目的地的身體。即如果您只想獲得最終的URL,則可以用'HTTParty.head(url,{:maintain_method_across_redirects => true})替換'HTTPParty.get'調用' – 2014-06-05 16:00:41