Making HTTP HEAD request with timeout in Ruby

后端 未结 1 1139
傲寒
傲寒 2021-01-23 00:48

In a Rails app, I\'d like to make a HTTP HEAD request for a resource (a user-provided URL), to make sure that it exists. I\'d also like a timeout, to ensure that the method fail

相关标签:
1条回答
  • 2021-01-23 01:46

    Try this snippet:

    require 'net/http'
    
    Net::HTTP.start('www.some_site.com') do |http|
      http.open_timeout = 2
      http.read_timeout = 2
      req = Net::HTTP::Head.new('/')
      http.request(req).each { |k, v| puts "#{k}: #{v}" }
    end
    

    Hope this is what you're looking for.

    UPDATE

    Because there is head method that looks like

    def head(path, initheader = nil)
      request(Head.new(path, initheader))
    end
    

    You can also use this snippet:

    require 'net/http'
    
    Net::HTTP.start('www.rubyinside.com') do |http|
      http.open_timeout = 2
      http.read_timeout = 2
      http.head('/').each { |k, v| puts "#{k}: #{v}" }
    end
    
    0 讨论(0)
提交回复
热议问题