使用Ruby,获取给定URL的内容类型的最有效方法是什么?

使用Ruby获取给定URL的内容类型的最有效方法是什么?

如果我想要简单的代码,这就是我要做的事情:

require 'open-uri' str = open('http://example.com') str.content_type #=> "text/html" 

它的最大优点是重定向。

如果您正在检查一堆URL,则可能需要在找到所需内容后在句柄上调用close

看看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']