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

折月煮酒 提交于 2019-11-27 23:14:17

问题


If http://foo.com redirects to 1.2.3.4 which then redirects to http://finalurl.com, how can I use Ruby to find out the landing URL "http://finalurl.com"?


回答1:


Here's two ways, using both HTTPClient and Open-URI:

require 'httpclient'
require 'open-uri'

URL = 'http://www.example.org'

httpc = HTTPClient.new
resp = httpc.get(URL)
puts resp.header['Location']
>> http://www.iana.org/domains/example/

open(URL) do |resp|
  puts resp.base_uri.to_s
end
>> http://www.iana.org/domains/example/



回答2:


Another way, using Curb:

def get_redirected_url(your_url)
  result = Curl::Easy.perform(your_url) do |curl|
    curl.follow_location = true
  end
  result.last_effective_url
end 



回答3:


for JRuby this worked

def get_final_url (url)
    final_url = ""
    until url.nil? do
      final_url = url
      url = Net::HTTP.get_response(URI.parse(url))['location']
    end

    final_url
  end



回答4:


I have implemented a RequestResolver for my need:

https://gist.github.com/lulalala/6be104641bcb60f9d0e8

It uses Net::HTTP, and follows multiple redirects. It also handles relative redirects. It was for my simple need so may have bugs. If you discover one please tell me.




回答5:


I'm not much of a Ruby user, but what you basically need is something to interpret HTTP headers. The following library appears to do that:

http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html

Skip down to "following redirection."



来源:https://stackoverflow.com/questions/4867652/how-can-i-get-the-final-url-after-redirects-using-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!