ruby​​ httparty获得帖子后的回复url或id

问题描述:

如何在做一个帖子后,在一个单独的脚本中使用httparty从一个rails项目获取响应url或id?ruby​​ httparty获得帖子后的回复url或id

Ruby脚本:

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

response.body和所有其他的人不显示的URL和响应ID

这个工作对我来说,可能有一个更好的办法,虽然这样做..

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

不幸的是,这些信息没有保存的HTTParty。当它遇到重定向时,它将遵循重定向并返回该请求的结果。它不会保存原始请求中的任何信息。好消息是,这样的行为是(通常)可预测的。 Web应用程序通常在向URL发送请求后重定向到相同的东西。

但是,如果你真的想这样做,你将不得不使用Ruby附带的net/http库。虽然没有比HTTParty更难,所以没有太多的工作。

+2

感谢您的答复,这是有道理的 - 但我没有想出一个办法做到这一点..这是一个有点古怪,但 – nictrix 2010-08-23 15:25:07

两年后,我发现了一种从上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