Search code examples
rubyrestrest-client

Find the redirect-url for POST request in rest-client


I need to get the redirect url name for the POST request i am making.

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

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

What i need is just the uri : www.abcd.com/971939frwddm

My question is whether i can get the uri directly from object e without regexing the string ?


Solution

  • This should work:

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

    Update
    Since the above did not work, I suggest you try:

    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
    

    (this is a combination of the suggested implementation of how to follow redirection on all request types and Request's implementation of follow_redirection