在rest-client中找到POST请求的redirect-url

时间:2014-04-18 07:56:41

标签: ruby rest rest-client

我需要获取我正在制作的POST请求的重定向url名称。

begin
  RestClient.post url, :param => p
rescue => e
  e.inspect
end

响应: "302 Found: <html><body>You are being <a href=\"https://www.abcd.com/971939frwddm\">redirected</a>.</body></html>\n"

我需要的只是uri:www.abcd.com/971939frwddm

我的问题是我是否可以直接从对象e获取uri而不重新编写字符串?

2 个答案:

答案 0 :(得分:4)

这应该是work

begin
  RestClient.post url, :param => p
rescue Redirect => e
  redirected_url = e.url
end

<强>更新
由于以上不起作用,我建议你试试:

RestClient.post(url, :param => p) do |response, request, result, &block|
  if [301, 302, 307].include? response.code
    redirected_url = response.headers[:location]
  else
    response.return!(request, result, &block)
  end
end

(这是follow redirection on all request typesRequest follow_redirection

的实施建议实施方式的组合

答案 1 :(得分:2)

万一有人遇到类似的东西,并希望在重定向后获得最终的网址,以下内容对我有效。

result = RestClient.get(url, :user_agent => AGENT, :cookies => @cookies){ |response, request, result, &block|
  if [301, 302, 307].include? response.code
    response.follow_redirection(request, result, &block)
  else
    final_url = request.url
    response.return!(request, result, &block)
  end
}

final_url将包含最终的redirect_url