我遇到了问题,因为我试图连接的主机并不总是可用的。我使用这段代码连接到主机:
begin #To catch error from Net::HTTP
net = Net::HTTP.new(uri.host, uri.port)
net.read_timeout = 5
net.continue_timeout = 5
res = net.start {|http|
http_request = http.request(req)
case http_request.response
case
...
else
@error_msg = "Response not handled by appliaction" << http_request.code << " " << http_request.message
end
}
rescue SocketError => se
@error_msg = "Net::SocketError #{se} (Perhaps host is down?)"
puts @error_msg
end
问题是,当主机没有响应(或其他问题)时,连接似乎运行得太长了。我希望能等5秒钟,但它正在努力做多:
Completed 500 Internal Server Error in 126302ms
Errno::ETIMEDOUT - Connection timed out - connect(2):
如何设置Net:HTTP对象的最大超时?
感谢
正如Ascar所指出的,这是错误的语法。但是:read_timeout本身并不能解决问题,如果主机根本没有响应,我还需要添加:open_timeout。
Net::HTTP.start(uri.host, uri.port, {read_timeout: 5, open_timeout: 5})
您正在做的是ruby 1.8
之前支持的方法
对于ruby > 1.9
,您应该将其用作启动选项。
试试这个:
res = net.start(:read_timeout => 5) { |http| # your block }
参见网络:HTTP.start