Net::HTTP reponse method - custom timeout

3,669 views
Skip to first unread message

Rob Nichols

unread,
Nov 28, 2007, 7:22:14 AM11/28/07
to rubyonra...@googlegroups.com
I am using the following code to control an external device via it's
in-built web server interface:

def send_to_unit(instruction)
begin
if @address and http = Net::HTTP.new(@address, 80)
http.start do |http|
request = Net::HTTP::Get.new(instruction)
request.basic_auth USERNAME, PASSWORD
response = http.request(request)
find_state(response.body)
end
end
rescue
#Connection failed
return nil
end
end

This works fine when the unit is working, but if someone switches the
unit off, it takes a long time (30-40 sec!) to time out.

Is there a way to specify a timeout period for the request? Net::HTTP
has a read_timeout attribute, but I can see how to use it, if this is
the approach to take.
--
Posted via http://www.ruby-forum.com/.

Frederick Cheung

unread,
Nov 28, 2007, 8:39:50 AM11/28/07
to rubyonra...@googlegroups.com

On 28 Nov 2007, at 12:22, Rob Nichols wrote:

>
> Is there a way to specify a timeout period for the request? Net::HTTP
> has a read_timeout attribute, but I can see how to use it, if this is
> the approach to take.

Here's what I've got

http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = x
http.read_timeout = y
response = http.start do |http|
http.request_get(path)
end

Rob Nichols

unread,
Nov 28, 2007, 9:02:13 AM11/28/07
to rubyonra...@googlegroups.com
Thank you Frederick,

This now works:

def send_to_unit(instruction)
begin
if @address and http = Net::HTTP.new(@address, 80)

http.open_timeout = 3
http.read_timeout = 3


http.start do |http|
request = Net::HTTP::Get.new(instruction)
request.basic_auth USERNAME, PASSWORD
response = http.request(request)
find_state(response.body)
end
end

rescue Timeout::Error
#Connection failed
return "not available - connection timed out"
end
end

Annoyingly - I looked at this post before I posted and the answer was
all there if I'd look at it more closely:

http://www.ruby-forum.com/topic/128439

So thank you for pointing me in the right direction. Splendid!

Reply all
Reply to author
Forward
0 new messages