如何在RestClient中使用以下内容重定向URL

时间:2016-09-01 19:12:35

标签: ruby redirect rest-client

if resp.code == 302
   resp.follow_redirection(req, result, &block)
else
   final_url = req.url
   resp.return!(req, result, &block)
   final_url
end

这可以获取重定向网址。但是如何在不遵循重定向的情况下获得它

3 个答案:

答案 0 :(得分:2)

在rest-client 2.0中,您还可以传递max_redirects: 0并从RestClient::MovedPermanently或其他重定向异常对象获取响应:

begin
  RestClient::Request.execute(method: :get, url: 'http://google.com',
                              max_redirects: 0)
rescue RestClient::ExceptionWithResponse => err
  puts err.response.inspect
  if err.response.code == 302
    puts err.response.headers[:location]
  end
end

=> <RestClient::Response 301 "<HTML><HEAD...">

答案 1 :(得分:1)

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

答案 2 :(得分:0)

resp = RestClient.get(url) do |response, request, result, &block|
  if [301, 302, 307].include? response.code
    # do not redirect
    response
  else
    response.return!(request, result, &block)
  end
end
res.headers[:location]