在Ruby 1.9.3中设置HTTP超时 [英] Setting an HTTP Timeout in Ruby 1.9.3
本文介绍了在Ruby 1.9.3中设置HTTP超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Ruby 1.9.3,需要获取URL.我可以使用Net::HTTP
进行此操作,但是,如果站点关闭,则Net::HTTP
最终会挂起.
I'm using Ruby 1.9.3 and need to GET a URL. I have this working with Net::HTTP
, however, if the site is down, Net::HTTP
ends up hanging.
在搜索互联网时,我已经看到许多人都面临着类似的问题,所有问题都带有骇人听闻的解决方案.但是,这些帖子中有很多都是很老的.
While searching the internet, I've seen many people faced similar problems, all with hacky solutions. However, many of those posts are quite old.
要求:
- 我希望使用
Net::HTTP
来安装新的gem. - 我需要正文和响应代码. (例如200)
- 我不想
require open-uri
,因为那样会进行全局更改并引发一些安全问题. - 我需要在X秒内获取一个URL,否则返回错误.
- I'd prefer using
Net::HTTP
to installing a new gem. - I need both the Body and the Response Code. (e.g. 200)
- I do not want to
require open-uri
, since that makes global changes and raises some security issues. - I need to GET a URL within X seconds, or return error.
使用Ruby 1.9.3,如何在设置超时时获取URL?
Using Ruby 1.9.3, how can I GET a URL while setting a timeout?
为澄清起见,我现有的代码如下:
To clarify, my existing code looks like:
Net::HTTP.get_response(URI.parse(url))
尝试添加:
Net::HTTP.open_timeout(1000)
结果:
NoMethodError: undefined method `open_timeout' for Net::HTTP:Class
推荐答案
You can set the open_timeout
attribute of the Net::HTTP
object before making the connection.
uri = URI.parse(url)
Net::HTTP.new(uri.hostname, uri.port) do |http|
http.open_timeout = 1000
response = http.request_get(uri.request_uri)
end
这篇关于在Ruby 1.9.3中设置HTTP超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文