class HTTPConn
Connection allows the creation of an HTTP/HTTPS connection
that allows the issues of HTTP requests.
Attributes
settings[RW]
url[R]
Public Class Methods
new(url, settings = {})
click to toggle source
# File lib/http_conn.rb, line 10 def initialize(url, settings = {}) @started = false @http = nil @url = url self.settings = { header: {}, ssl: false, cert: "", read_timeout: 60 } self.settings.merge!(settings) end
Public Instance Methods
get(options = {})
click to toggle source
# File lib/http_conn.rb, line 24 def get(options = {}) default = { end_point: "", header: {}, query_str: {} } options = default.merge(options) url = query_str("#{@url}#{options[:end_point]}", options[:query_str]) uri = URI(url) http = @started ? @http : get_http(uri) request = Net::HTTP::Get.new(uri.request_uri, settings[:header].merge(options[:header])) http.request(request) end
post(options = {})
click to toggle source
# File lib/http_conn.rb, line 40 def post(options = {}) default = { end_point: "", header: {}, body: nil } options = default.merge(options) uri = URI("#{@url}#{options[:end_point]}") http = @started ? @http : get_http(uri) request = Net::HTTP::Post.new(uri.request_uri, settings[:header].merge(options[:header])) http.request(request, options[:body]) end
start(uri = nil) { || ... }
click to toggle source
# File lib/http_conn.rb, line 55 def start(uri = nil) @started = true @http = uri.nil? ? get_http(URI(@url)) : get_http(URI(uri)) @http.start yield @http.finish # Close connection after usage in 'yield'. @started = false end
Private Instance Methods
get_http(uri)
click to toggle source
# File lib/http_conn.rb, line 79 def get_http(uri) http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = settings[:read_timeout] if settings[:ssl] http.use_ssl = true if settings[:cert].empty? http.verify_mode = OpenSSL::SSL::VERIFY_NONE else http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.cs_file = settings[:cert] end end http end
query_str(url, data)
click to toggle source
# File lib/http_conn.rb, line 66 def query_str(url, data) unless data.empty? first = data.keys[0] url = "#{url}?#{first}=#{data[first]}" data.each_key do |key| next if key == first url = "#{url}&#{key}=#{data[key]}" end end url end