使用Rails在Net :: HTTP :: Get.new中设置自定义超时 [英] Set custom timeout in Net::HTTP::Get.new with Rails
本文介绍了使用Rails在Net :: HTTP :: Get.new中设置自定义超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此代码来抓取外部html文件
I'm using this code to scraping external html files
link = URI.parse(url)
request = Net::HTTP::Get.new(link.path)
response = Net::HTTP.start(link.host, link.port) {|http|
http.request(request)
}
工作得很好,但网页速度慢有时会响应超时,所以我需要为每个连接设置一个超时限制。有什么想法吗?
Works great but with slowed web pages sometimes responds timeout, so I need set a timeout limit per connection. Any idea?
推荐答案
你需要设置read_timeout属性。
You need to set the read_timeout attribute.
link = URI.parse(url)
request = Net::HTTP::Get.new(link.path)
begin
response = Net::HTTP.start(link.host, link.port) {|http|
http.read_timeout = 100 #Default is 60 seconds
http.request(request)
}
rescue Net::ReadTimeout => e
puts e.message
end
这篇关于使用Rails在Net :: HTTP :: Get.new中设置自定义超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文