Ruby:使用openuri 发送http请求超时
伊谢尔伦
伊谢尔伦 2017-04-22 08:56:03
[Ruby讨论组]

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

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
ringa_lee

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证书等等。
具体的可以参考文档,这里就不多说了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号