我遇到麻烦,我试图连接的主机总是无法使用。 我使用这段代码,我连接到主机:
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对象的最大超时时间?
由于
答案 0 :(得分:2)
您正在做的是ruby 1.8
对于ruby > 1.9
,您应该将其用作开始选项。
试试这个:
res = net.start(:read_timeout => 5) { |http| # your block }
答案 1 :(得分:0)
Ascar指出,这是错误的语法。 但是:read_timeout单独没有解决问题,我还需要添加:open_timeout如果主机根本没有响应。
Net::HTTP.start(uri.host, uri.port, {read_timeout: 5, open_timeout: 5})