在Ruby中获取URL的重定向

根据Facebook图形API,我们可以使用此示例请求用户个人资料图片(示例):

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

但是上一个链接的真实图像URL是:

http://sofzh.miximages.com/ruby-on-rails/41721_1489686594_527_q.jpg

如果您在浏览器上键入第一个链接,它会将您重定向到第二个链接。

有没有办法通过知道第一个URL来获取Ruby / Rails的完整URL(第二个链接)?

(这是这个问题的重复,但对Ruby而言)

您可以使用Net :: Http并从响应中读取Location:标头

 require 'net/http' require 'uri' url = URI.parse('http://www.example.com/index.html') res = Net::HTTP.start(url.host, url.port) {|http| http.get('/index.html') } res['location'] 

这已经得到了正确回答,但有一个更简单的方法:

 res = Net::HTTP.get_response(URI('https://graph.facebook.com/1489686594/picture')) res['location'] 

你有HTTPS URL,所以你将处理…

 require 'net/http' require 'net/https' if RUBY_VERSION < '1.9' require 'uri' u = URI.parse('https://graph.facebook.com/1489686594/picture') h = Net::HTTP.new u.host, u.port h.use_ssl = u.scheme == 'https' head = h.start do |ua| ua.head u.path end puts head['location'] 

我知道这是一个老问题,但我会为后人添加这个答案:

我见过的大多数解决方案只遵循一次重定向。 就我而言,我必须遵循多个重定向才能获得实际的最终目标url。 我使用Curl(通过Curb gem )就像这样:

 result = Curl::Easy.perform(url) do |curl| curl.head = true curl.follow_location = true end result.last_effective_url 

您可以检查响应状态代码并使用get_final_redirect_url方法以递归方式获取最终URL:

  require 'net/http' def get_final_redirect_url(url, limit = 10) uri = URI.parse(url) response = ::Net::HTTP.get_response(uri) if response.class == Net::HTTPOK return uri else redirect_location = response['location'] location_uri = URI.parse(redirect_location) if location_uri.host.nil? redirect_location = uri.scheme + '://' + uri.host + redirect_location end warn "redirected to #{redirect_location}" get_final_redirect_url(redirect_location, limit - 1) end end 

我面临同样的问题。 我解决了它并围绕它构建了一个gem final_redirect_url ,这样每个人都可以从中受益。

您可以在此处找到有关使用的详细信息。

是的,“位置”响应标题告诉您实际的图像URL。

但是,如果您在网站上将图片用作用户的个人资料图片,我建议您使用“https://graph.facebook.com/:user_id/picture”样式url而不是实际图片url。 否则,您的用户将来会看到大量“未找到”的图片或过时的个人资料图片。

你只需将“https://graph.facebook.com/:user_id/picture”作为“img”标签的“src”属性。 他们浏览器获取用户的更新图像。

PS。 我在Twitter和Yahoo!网站上遇到了这样的麻烦。 OpenID现在..