在Ruby中获取URL的重定向

neo*_*eon 26 ruby ruby-on-rails

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

https://graph.facebook.com/1489686594/picture
Run Code Online (Sandbox Code Playgroud)

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

http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs356.snc4/41721_1489686594_527_q.jpg

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

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

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

Fel*_*peC 42

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

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

  • 这很好,但它只遵循一个重定向级别:( (5认同)
  • 发布一个占用空间不到20%的解决方案的+1,但完成同样的事情. (3认同)

Mic*_*ile 13

您可以使用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']
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用url.request_uri而不是'/index.html'. (3认同)
  • 如果有多个重定向怎么办?会得到最后一个吗?还是只是第一个? (2认同)

sma*_*thy 9

你有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']
Run Code Online (Sandbox Code Playgroud)