如何在Ruby中设置代理连接的超时

时间:2013-01-27 22:04:21

标签: ruby-on-rails ruby http

我知道如何通过代理请求set the open/read timeout。然而,我的问题是我的代理偶尔会关闭,因此我无法连接到代理。所以我希望能够将连接到代理的超时设置为某个值,然后通过尝试其他方式来处理超时。知道如何设置连接到http代理的超时值吗?谢谢!

1 个答案:

答案 0 :(得分:0)

首先是代码,然后在下面进行一些解释:

# get an instance of Net::HTTP that has proxy settings embedded
# see the source:  http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-Proxy
proxyclass = Net::HTTP::Proxy("proxy_host");

# Create a new instance of the URL you want to connect to
# NOTE: no connection is attempted yet
proxyinstance = proxyclass.new("google.com");

# Make your setting changes, specifically the timeouts
proxyinstance.open_timeout = 5;
proxyinstance.read_timeout = 5;

# now, attempt connecting through the proxy with the desired
# timeout settings.
proxyinstance.start do |http|
    # do something with the http instance
end

关键是实现open_timeoutread_timeout是实例变量,而Net::HTTP::Proxy实际上返回一个装饰的Net::HTTP类。

您会遇到类似Net::HTTP用法的同一问题。您必须以“长”方式构建它,而不是使用Net::HTTP.start()类方法快捷方式。