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

 欣欣大妮 发布于 2022-10-27 12:37

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

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

2 个回答
  • 不需要这么麻烦,使用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证书等等。
    具体的可以参考文档,这里就不多说了。

    2022-10-28 11:11 回答
  • 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
    
    2022-10-28 11:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有