class Fbox::HttpClient

Attributes

options[R]

Public Class Methods

new(options) click to toggle source
# File lib/fbox/http_client.rb, line 32
def initialize(options)
  @options = options
  @options.freeze
  @cookies = {}
end

Public Instance Methods

http_conn(uri) click to toggle source
# File lib/fbox/http_client.rb, line 49
def http_conn(uri)
  if @options[:proxy_address]
      http_class = Net::HTTP::Proxy(@options[:proxy_address], @options[:proxy_port] ? @options[:proxy_port] : 80)
  else
      http_class = Net::HTTP
  end
  http_conn = http_class.new(uri.host, uri.port)
  http_conn.use_ssl = @options[:use_ssl]
  http_conn.verify_mode = @options[:ssl_verify_mode]
  http_conn
end
make_request(http_method, path, body='', headers={}, form_params = {}) click to toggle source
# File lib/fbox/http_client.rb, line 38
def make_request(http_method, path, body='', headers={}, form_params = {})
  request = Net::HTTP.const_get(http_method.to_s.capitalize).new(path, headers)
  request.body = body unless body.nil?
  add_cookies(request) if options[:use_cookies]
  request.set_form_data(form_params) if !form_params.empty? && http_method.to_s.capitalize == 'Post'
  
  response = http_conn(uri).request(request)
  store_cookies(response) if options[:use_cookies]
  response
end
request(*args) click to toggle source
# File lib/fbox/http_client.rb, line 65
def request(*args)
  response = make_request(*args)
  raise HTTPError.new(response) unless response.kind_of?(Net::HTTPSuccess)
  response
end
uri() click to toggle source
# File lib/fbox/http_client.rb, line 61
def uri
  URI.parse(@options[:site])
end

Private Instance Methods

add_cookies(request) click to toggle source
# File lib/fbox/http_client.rb, line 83
def add_cookies(request)
  cookie_array = @cookies.values.map { |cookie| cookie.to_s }
  request.add_field('Cookie', cookie_array.join('; ')) if cookie_array.any?
  request
end
store_cookies(response) click to toggle source
# File lib/fbox/http_client.rb, line 72
def store_cookies(response)
  cookies = response.get_fields('set-cookie')
  if cookies
    cookies.each do |cookie|
      data = CGI::Cookie.parse(cookie)
      data.delete('Path')
      @cookies.merge!(data)
    end
  end
end