【发布时间】:2010-08-23 07:12:50
【问题描述】:
在发布后,如何在单独的脚本中使用 httparty 从 rails 项目获取响应 url 或 id?
红宝石脚本:
HTTParty.post('http://localhost:3000/change_logs', parameters)
response.body 和所有其他的不显示 url 和响应 id
【问题讨论】:
在发布后,如何在单独的脚本中使用 httparty 从 rails 项目获取响应 url 或 id?
红宝石脚本:
HTTParty.post('http://localhost:3000/change_logs', parameters)
response.body 和所有其他的不显示 url 和响应 id
【问题讨论】:
两年后,我找到了一种从response 上的request 属性访问最后一个URI 的方法:
url = "http://example.com/redirects/to/www"
response = HTTParty.get(url)
response.request.last_uri.to_s
# => "http://www.example.com"
【讨论】:
HTTPParty.get 调用替换为 HTTParty.head(url, { :maintain_method_across_redirects => true })
很遗憾,HTTParty 不保留该信息。当它遇到重定向时,它将跟随重定向并返回该请求的结果。它不会保存原始请求中的任何信息。
好消息是,这样的行为(通常)是可以预测的。 Web 应用程序通常会在向 URL 发送请求后重定向到相同的内容。
但如果你真的想这样做,你将不得不使用 Ruby 附带的 net/http 库。不过,它并不比 HTTParty 难多少,所以工作量也不大。
【讨论】:
这对我有用,但可能有更好的方法来做到这一点..
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
【讨论】: