1

我知道如何为通过代理的请求设置打开/读取超时。然而,我的问题是我的代理偶尔会出现故障,因此我无法连接到代理。所以我希望能够将连接到代理的超时设置为某个值,然后通过尝试其他方法来处理超时。知道如何设置连接到 http 代理的超时值吗?谢谢!

4

1 回答 1

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()类方法快捷方式。

于 2013-01-28T03:21:05.603 回答