我知道如何通过代理请求set the open/read timeout。然而,我的问题是我的代理偶尔会关闭,因此我无法连接到代理。所以我希望能够将连接到代理的超时设置为某个值,然后通过尝试其他方式来处理超时。知道如何设置连接到http代理的超时值吗?谢谢!
答案 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_timeout
和read_timeout
是实例变量,而Net::HTTP::Proxy
实际上返回一个装饰的Net::HTTP
类。
您会遇到类似Net::HTTP
用法的同一问题。您必须以“长”方式构建它,而不是使用Net::HTTP.start()
类方法快捷方式。