How can I get the final URL after redirects using Ruby?

URL redirects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require 'net/http'
require 'uri'
class UrlUtils
def self.get_final_url(url)
exit = false
while exit==false
r = Net::HTTP.get_response(URI.parse(url))
resp = r.inspect.to_s
if (resp.include? '301') || (resp.include? '302')
url = r['location']
else
exit = true
end
end
url
end
end
url = 'http://bit.ly/2ecC7Cc'
print url + ' -> '
final_url = UrlUtils.get_final_url(url)
puts final_url
Share