下面在调用币安的接口时,经常会卡住,设置连接超时也不会抛出异常,代码如下(默认连接超时为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