Mla*_*vić 23

require 'net/http'
require 'uri'

Net::HTTP.get_response(URI.parse('http://t.co/yjgxz5Y'))['location']
# => "http://nickstraffictricks.com/4856_how-to-rank-1-in-google/" 
Run Code Online (Sandbox Code Playgroud)

  • 根据文档,Net :: HTTP不执行递归重定向,如果重定向被重定向,这是必需的.这看起来只会处理第一个. (2认同)

the*_*Man 8

我已经习惯open-uri了,因为它很简单.它将检索页面,但也会遵循多个重定向:

require 'open-uri'

final_uri = ''
open('http://t.co/yjgxz5Y') do |h|
  final_uri = h.base_uri
end
final_uri # => #<URI::HTTP:0x00000100851050 URL:http://nickstraffictricks.com/4856_how-to-rank-1-in-google/>
Run Code Online (Sandbox Code Playgroud)

文档显示了使用较低级Net :: HTTP处理重定向的一个很好的示例.

require 'net/http'
require 'uri'

def fetch(uri_str, limit = 10)
  # You should choose better exception.
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0

  response = Net::HTTP.get_response(URI.parse(uri_str))
  case response
  when Net::HTTPSuccess     then response
  when Net::HTTPRedirection then fetch(response['location'], limit - 1)
  else
    response.error!
  end
end

puts fetch('http://www.ruby-lang.org')
Run Code Online (Sandbox Code Playgroud)

当然,如果页面没有使用HTTP重定向,这一切都会崩溃.许多网站使用元重定向,您必须通过从元标记中检索URL来处理,但这是一个不同的问题.


Spy*_*ros 1

您必须遵循重定向。我认为这会有所帮助:

http://shadow-file.blogspot.com/2009/03/handling-http-redirection-in-ruby.html