首页 > Ruby:使用openuri 发送http请求超时

Ruby:使用openuri 发送http请求超时

在官方文档看了下,好像openuri默认不支持timeout吧?
http://www.ruby-doc.org/stdlib-2.1.1/libdoc/open-uri/rdoc/OpenURI.html

如果不能设置timeout的话,有替代品吗?


https://github.com/lostisland/faraday

conn.get do |req|
  req.url '/search'
  req.options.timeout = 5           # open/read timeout in seconds
  req.options.open_timeout = 2      # connection open timeout in seconds
end

不需要这么麻烦,使用Net::HTTP就可以了

uri=URI(query_uri)
Net::HTTP.get(uri,:read_timeout=>30)

这个是文档介绍:

open_timeout[RW]
Number of seconds to wait for the connection to open. Any number may be used, including Floats for fractional seconds. If the HTTP object cannot open a connection in this many seconds, it raises a Net::OpenTimeout exception. The default value is nil.

顺带翻译一下好了:

open_timeout
设定打开一个连接时最大的等待时间。它的值可以是任何数字,包括很小的浮点数。如果在设定的时间期限内打不开连接的画会抛出一个Net::OpenTimeout异常。默认值是nil,也就是不限制时间。
这样就会限制30秒内完成请求了。

另外还有很多其他功能,例如设定代理服务器,CA证书,ssl证书等等。
具体的可以参考文档,这里就不多说了。

【热门文章】
【热门文章】