使用Ruby获取给定URL的内容类型的最有效方法是什么?
答案 0 :(得分:13)
如果我想要简单的代码,这就是我要做的事情:
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
最大的优点是它遵循重定向。
如果您正在查看大量网址,则可能需要在找到所需内容后在句柄上调用close
。
答案 1 :(得分:3)
查看Net::HTTP库。
require 'net/http'
response = nil
uri, path = 'google.com', '/'
Net::HTTP.start(uri, 80) { |http| response = http.head(path) }
p response['content-type']