Class: SimpleHttp::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_http/connection.rb

Defined Under Namespace

Classes: UnhandledHTTPMethodError, UnsupportedSchemeError

Constant Summary collapse

NET_HTTP_EXCEPTIONS =
[
  EOFError,
  Errno::ECONNABORTED,
  Errno::ECONNREFUSED,
  Errno::ECONNRESET,
  Errno::EINVAL,
  Net::HTTPBadResponse,
  Net::HTTPHeaderSyntaxError,
  Net::ProtocolError,
  SocketError,
  Zlib::GzipFile::Error,
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ Connection

Returns a new instance of Connection.



46
47
48
49
50
51
# File 'lib/simple_http/connection.rb', line 46

def initialize(url, options={})
  @uri = Addressable::URI.parse(url)
  self.class.default_options.keys.each do |key|
    instance_variable_set(:"@#{key}", options.fetch(key, self.class.default_options[key]))
  end
end

Instance Attribute Details

#acceptObject

Returns the value of attribute accept.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def accept
  @accept
end

#configObject

Returns the value of attribute config.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def config
  @config
end

#headersObject

Returns the value of attribute headers.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def headers
  @headers
end

#hostObject

Returns the value of attribute host.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def host
  @host
end

#max_redirectsObject

Returns the value of attribute max_redirects.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def max_redirects
  @max_redirects
end

#portObject

Returns the value of attribute port.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def port
  @port
end

#schemeObject

Returns the value of attribute scheme.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def scheme
  @scheme
end

#sslObject

Returns the value of attribute ssl.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def ssl
  @ssl
end

#uriObject

Returns the value of attribute uri.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def uri
  @uri
end

#user_agentObject

Returns the value of attribute user_agent.



30
31
32
# File 'lib/simple_http/connection.rb', line 30

def user_agent
  @user_agent
end

Class Method Details

.default_optionsObject



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/simple_http/connection.rb', line 33

def self.default_options
  {
    :headers => {
      'Accept'     => 'application/json',
      'User-Agent' => "Simple HTTP gem #{SimpleHttp::Version}",
      'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3'

    },
    :ssl => {:verify => true},
    :max_redirects => 5
  }
end

Instance Method Details

#absolute_url(path = '') ⇒ Object



77
78
79
# File 'lib/simple_http/connection.rb', line 77

def absolute_url(path='')
  "#{scheme}://#{host}#{path}"
end

#default_headersObject



53
54
55
# File 'lib/simple_http/connection.rb', line 53

def default_headers
  self.class.default_options[:headers]
end

#http_connection(opts = {}) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/simple_http/connection.rb', line 90

def http_connection(opts={})
  _host   = opts[:host]   || host
  _port   = opts[:port]   || port
  _scheme = opts[:scheme] || scheme

  @http_client = Net::HTTP.new(_host, _port)

  configure_ssl(@http_client) if _scheme == 'https'

  @http_client
end

#send_request(method, path, opts = {}) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/simple_http/connection.rb', line 102

def send_request(method, path, opts={})
  headers         = @headers.merge(opts.fetch(:headers, {}))
  params          = opts[:params] || {}
  query           = Addressable::URI.form_encode(params)
  method          = method.to_sym
  normalized_path = query.empty? ? path : [path, query].join("?")
  client          = http_connection(opts.fetch(:connection_options, {}))

  if (method == :post || method == :put)
    headers['Content-Type'] ||= 'application/x-www-form-urlencoded'
  end

  case method
  when :get, :delete
    response = client.send(method, normalized_path, headers)
  when :post, :put
    response = client.send(method, path, query, headers)
  else
    raise UnhandledHTTPMethodError.new("Unsupported HTTP method, #{method}")
  end

  status = response.code.to_i

  case status
  when 301, 302, 303, 307
    unless redirect_limit_reached?
      if status == 303
        method = :get
        params = nil
        headers.delete('Content-Type')
      end
      redirect_uri = Addressable::URI.parse(response.header['Location'])
      conn = {
        :scheme => redirect_uri.scheme,
        :host   => redirect_uri.host,
        :port   => redirect_uri.port
      }
      return send_request(method, redirect_uri.path, :params => params, :headers => headers, :connection_options => conn)
    end
  when 100..599
    @redirect_count = 0
  else
    raise "Unhandled status code value of #{response.code}"
  end
  response
rescue *NET_HTTP_EXCEPTIONS
  raise "Error::ConnectionFailed, #{$!}"
end

#ssl?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/simple_http/connection.rb', line 81

def ssl?
  scheme == "https" ? true : false
end