Using Ruby, what is the most efficient way to get the content type of a given URL?
What is the most efficient way to get the content-type of a given URL usin开发者_Go百科g Ruby?
This is what I'd do if I want simple code:
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
The big advantage is it follows redirects.
If you're checking a bunch of URLs you might want to call close
on the handles after you've found what you want.
Take a look at the Net::HTTP library.
require 'net/http'
response = nil
uri, path = 'google.com', '/'
Net::HTTP.start(uri, 80) { |http| response = http.head(path) }
p response['content-type']
精彩评论