Get redirect of a URL in Ruby

后端 未结 7 1290
盖世英雄少女心
盖世英雄少女心 2020-12-02 23:18

According to Facebook graph API we can request a user profile picture with this (example):

https://graph.facebook.com/1489686594/picture

Bu

7条回答
  •  难免孤独
    2020-12-02 23:56

    If you want a solution that:

    • does not use gems
    • follows all redirects
    • works also with url-shortening services
    require 'net/http'
    require 'uri'
    
    def follow_redirections(url)   
      response = Net::HTTP.get_response(URI(url))
      until response['location'].nil?
        response = Net::HTTP.get_response(URI(response['location']))
      end
      response.uri.to_s
    end
    
    # EXAMPLE USAGE
    follow_redirections("https://graph.facebook.com/1489686594/picture") 
    # => https://static.xx.fbcdn.net/rsrc.php/v3/yo/r/UlIqmHJn-SK.gif
    

提交回复
热议问题