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

前端 未结 4 2113
北荒
北荒 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:43

    For resolving redirects you should use a HEAD request to avoid downloading the whole response body (imagine resolving a URL to an audio or video file).

    Working example using the Faraday gem:

    require 'faraday'
    require 'faraday_middleware'
    
    def resolve_redirects(url)
        response = fetch_response(url, method: :head)
        if response
            return response.to_hash[:url].to_s
        else
            return nil
        end
    end
    
    def fetch_response(url, method: :get)
        conn = Faraday.new do |b|
            b.use FaradayMiddleware::FollowRedirects;
            b.adapter :net_http
        end
        return conn.send method, url
    rescue Faraday::Error, Faraday::Error::ConnectionFailed => e
        return nil
    end
    
    puts resolve_redirects("http://cre.fm/feed/m4a") # http://feeds.feedburner.com/cre-podcast
    

提交回复
热议问题