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

This works to get the redirect URL. But how to get it without following redirects

user3636388
  • 187
  • 2
  • 24

3 Answers3

2
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
Ross Worth
  • 56
  • 6
2

In rest-client 2.0, you can also pass max_redirects: 0 and get the response from the RestClient::MovedPermanently or other redirect exception object:

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...">
A B
  • 8,340
  • 2
  • 31
  • 35
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]
Pikachu
  • 774
  • 13
  • 15