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

查看:175
本文介绍了在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 方法看起来像

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天全站免登陆