Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom timeout in Net::HTTP::Get.new with Rails

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?

like image 444
skozz Avatar asked Jan 05 '14 16:01

skozz


1 Answers

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
like image 132
Kumar Akarsh Avatar answered Nov 12 '22 04:11

Kumar Akarsh