[Ruby] How to follow HTTP redirects and retrieve the final URL
In Ruby, you can use the Net::HTTP library to follow HTTP redirects and retrieve the final URL. Here’s how:
Method 1: Using Net::HTTP Manually
require 'net/http' require 'uri' def get_redirected_url(url) uri = URI.parse(url) response = Net::HTTP.get_response(uri) if response.is_a?(Net::HTTPRedirection) return response['location'] # The redirected URL else return url # No redirection, return original URL end end puts get_redirected_url("http://example.com")
This method fetches the response header and checks for redirection.
Method 2: Following Redirects Automatically
If you want to follow multiple redirects until you reach the final destination:
require 'net/http' require 'uri' def get_final_url(url, limit = 10) raise "Too many redirects" if limit == 0 uri = URI.parse(url) response = Net::HTTP.get_response(uri) case response when Net::HTTPRedirection new_url = response['location'] get_final_url(new_url, limit - 1) # Follow redirect else uri.to_s # Return final URL end end puts get_final_url("http://example.com")
This method follows up to 10 redirects.
Method 3: Using open-uri (Simpler Approach)
require 'open-uri' def get_redirected_url(url) URI.open(url) { |resp| resp.base_uri.to_s } end puts get_redirected_url("http://example.com")
This approach uses open-uri, which automatically follows redirects and returns the final URL.
Would you like a more advanced version with custom headers or cookies?
来自ChatGPT

浙公网安备 33010602011771号