下面在調用幣安的接口時,常常會卡住,設置鏈接超時也不會拋出異常,代碼以下(默認鏈接超時爲nil, 參考:https://github.com/ruby/ruby/pull/269):git
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中配置便可則會超時拋出異常,以下:github
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https', :open_timeout => 1) do |http| http.request(req) end