先吐槽一下百度,就是个坑,翻遍了百度都没翻到答案,还好谷歌给力。
有两个方法,第一:绕过restclient直接使用原生方法:
RestClient::Request.execute(:method => :post, :url => @url, :timeout => 90000000)
这样做的好处是不用重写restclient整个模块,可以直接使用,但我比较喜欢第二种方法,那就是重写restclient这个模块,代码如下:
require ‘net/http‘
require ‘openssl‘
require ‘stringio‘
require ‘uri‘
require ‘zlib‘
require ‘restclient‘
Timeout_vaule = 30
OpenTimeout_vaule = 30
module RestClient2
# include RestClient
def self.get(url, headers={}, &block)
RestClient::Request.execute(:method => :get, :url => url, :headers => headers, :timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.post(url, payload, headers={}, &block)
RestClient::Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.patch(url, payload, headers={}, &block)
RestClient::Request.execute(:method => :patch, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.put(url, payload, headers={}, &block)
RestClient::Request.execute(:method => :put, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.delete(url, headers={}, &block)
RestClient::Request.execute(:method => :delete, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.head(url, headers={}, &block)
RestClient::Request.execute(:method => :head, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
def self.options(url, headers={}, &block)
RestClient::Request.execute(:method => :options, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)
end
end
这样就可以直接如同使用原生的restclient一样去使用它,不过这样的话ruby自带的timeout这个东西就不太好使了,虽然原本就没好使过,所以需要捕获的异常就变成了:RestClient::RequestTimeout
当然,这个异常可能有其他捕获办法,但这个定位好像挺准的,所以就用这个了