Question

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 ?

Was it helpful?

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

OTHER TIPS

Just in case anyone runs into something similar and wants to get the final url after the redirect, the following worked for me.

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 will contain the final redirect_url

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top