如何在使用Ruby重定向后获取最终的URL?
如果http://foo.com
重定向到1.2.3.4
然后重定向到http://finalurl.com
,我如何使用Ruby找到登陆URL“http://finalurl.com”?
这里有两种方法,使用HTTPClient和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/
另一种方法,使用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
我已根据需要实现了RequestResolver:
https://gist.github.com/lulalala/6be104641bcb60f9d0e8
它使用Net :: HTTP,并遵循多个重定向。 它还处理相对重定向。 这是为了我的简单需要所以可能有bug。 如果你发现一个,请告诉我。
对于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
我不是一个Ruby用户,但你基本上需要的是解释HTTP头的东西。 以下库似乎是这样做的:
http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html
省略“跟随重定向”。