How do I get the destination URL of a shortened URL using Ruby?

前端 未结 4 2094
北荒
北荒 2021-01-04 06:59

How do I take this URL http://t.co/yjgxz5Y and get the destination URL which is http://nickstraffictricks.com/4856_how-to-rank-1-in-google/

4条回答
  •  春和景丽
    2021-01-04 07:36

    I've used open-uri for this, because it's nice and simple. It will retrieve the page, but will also follow multiple redirects:

    require 'open-uri'
    
    final_uri = ''
    open('http://t.co/yjgxz5Y') do |h|
      final_uri = h.base_uri
    end
    final_uri # => #
    

    The docs show a nice example for using the lower-level Net::HTTP to handle redirects.

    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')
    

    Of course this all breaks down if the page isn't using a HTTP redirect. A lot of sites use meta-redirects, which you have to handle by retrieving the URL from the meta tag, but that's a different question.

提交回复
热议问题