2016年2月3日 星期三

[Rails] 運用 Net::HTTP and URI

http = if Recaptcha.configuration.proxy proxy_server = URI.parse(Recaptcha.configuration.proxy) Net::HTTP::Proxy(proxy_server.host, proxy_server.port, proxy_server.user, proxy_server.password) else Net::HTTP end query = URI.encode_www_form(verify_hash) uri = URI.parse(Recaptcha.configuration.verify_url + '?' + query) http_instance = http.new(uri.host, uri.port) http_instance.read_timeout = http_instance.open_timeout = options[:timeout] || DEFAULT_TIMEOUT if uri.port == 443 http_instance.use_ssl = true http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE end request = Net::HTTP::Get.new(uri.request_uri) http_instance.request(request).body 


URI.encode_www_form: 把ruby hash 變成 string
ex: URI.encode_www_form(sss: '123', ggg: '456') => sss=123&ggg=456

URI.parse: 把網址變成物件.

設定 http_instance timeout 時間
http_instance.read_timeout = http_instance.open_timeout = 3 (seccond)
超出時間會拋出 Timeout::Error

【下列文章您可能也有興趣】

沒有留言: