如何在使用Ruby重定向后获取最终的URL?

时间:2011-02-01 20:32:54

标签: ruby networking redirect url-routing

如果http://foo.com重定向到1.2.3.4然后重定向到http://finalurl.com,我如何使用Ruby找到登陆网址“http://finalurl.com”?

4 个答案:

答案 0 :(得分:22)

以下两种方式,同时使用HTTPClientOpen-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/

答案 1 :(得分:1)

我已根据需要实施了RequestResolver:

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

它使用Net :: HTTP,并遵循多个重定向。它还处理相对重定向。 这是为了我的简单需要所以可能有bug。如果你发现一个,请告诉我。

答案 2 :(得分:1)

JRuby这项工作

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

答案 3 :(得分:0)

我不是一个Ruby用户,但你基本上需要的是解释HTTP头的东西。以下库似乎是这样做的:

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

请跳至“重定向后”。

相关问题