首頁  >  問答  >  主體

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

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

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

伊谢尔伦伊谢尔伦2712 天前555

全部回覆(2)我來回復

  • ringa_lee

    ringa_lee2017-04-22 08:58:03

    https://github.com/lostisland/faraday

    雷雷

    回覆
    0
  • 天蓬老师

    天蓬老师2017-04-22 08:58:03

    不需要這麼麻煩,使用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.Eout exception. .

    順帶翻譯一下好了:

    open_timeout
    設定開啟一個連線時最大的等待時間。它的值可以是任何數字,包括很小的浮點數。如果在設定的時間期限內打不開連接的畫會拋出一個Net::OpenTimeout異常。預設值是nil,也就是不限制時間。
    這樣就會限制30秒內完成請求了。

    另外還有很多其他功能,例如設定代理伺服器,CA證書,ssl證書等等。
    具體的可以參考文檔,這裡就不多說了。

    回覆
    0
  • 取消回覆