1. 程式人生 > >Ruby http/net 中連接超時問題

Ruby http/net 中連接超時問題

class cnblogs 卡住 json 參考 拋出異常 異常 api uri

下面在調用幣安的接口時,經常會卡住,設置連接超時也不會拋出異常,代碼如下(默認連接超時為nil, 參考:https://github.com/ruby/ruby/pull/269):

require ‘net/http‘
require ‘json‘
require ‘byebug‘

uri = URI(‘https://www.binance.com/api/v1/ticker/24hr?symbol=EOSBTC‘)

req = Net::HTTP::Get.new(uri)

loop do
  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == ‘https‘) do |http|
    http.open_timeout = 1
    http.request(req)
  end

  puts "#{JSON.parse res.body}"
  puts "http request complete."
  sleep 1
end

不知道為什麽,用 http.open_timeout = 1 這種設置不奏效,改為在start的options中配置即可則會超時拋出異常,如下:

  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == ‘https‘, :open_timeout => 1) do |http|
    http.request(req)
  end

Ruby http/net 中連接超時問題