在 Ruby 中发出超时的 HTTP HEAD 请求 [英] Making HTTP HEAD request with timeout in Ruby

查看:27
本文介绍了在 Ruby 中发出超时的 HTTP HEAD 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 应用程序中,我想对资源(用户提供的 URL)发出 HTTP HEAD 请求,以确保它存在.我还想要超时,以确保该方法在等待一段合理的时间后失败.实现此目的最直接的方法是什么(如果可能,使用标准库)?

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 fails after spending a reasonable period of time waiting. What is the most straightforward way to accomplish this (using the standard library, if possible)?

推荐答案

试试这个片段:

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.

更新

因为有 head 方法看起来像

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

这篇关于在 Ruby 中发出超时的 HTTP HEAD 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆