Class: JPush::Utils::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/jpush/utils/http.rb

Constant Summary collapse

DEFAULT_USER_AGENT =
'jpush-api-ruby-client/' + JPush::VERSION
DEFAULT_OPEN_TIMEOUT =
20
DEFAULT_READ_TIMEOUT =
120
DEFAULT_RETRY_TIMES =
3
RETRY_SLEEP_TIME =
3
HTTP_VERB_MAP =
{
  get:    Net::HTTP::Get,
  post:   Net::HTTP::Post,
  put:    Net::HTTP::Put,
  delete: Net::HTTP::Delete
}
DEFAULT_HEADERS =
{
  'user-agent' => DEFAULT_USER_AGENT,
  'accept' => 'application/json',
  'content-type' => 'application/json',
  'connection' => 'close'
}

Instance Method Summary collapse

Constructor Details

#initialize(method, url, params: nil, body: nil, headers: {}, opts: {}) ⇒ Http

Returns a new instance of Http.



29
30
31
32
33
34
35
36
37
# File 'lib/jpush/utils/http.rb', line 29

def initialize(method, url, params: nil, body: nil, headers: {}, opts: {})
  method = method.downcase.to_sym
  err_msg = "http method #{method} is not supported"
  raise Utils::Exceptions::JPushError, err_msg unless HTTP_VERB_MAP.keys.include?(method)
  @uri = URI(url)
  @uri.query = URI.encode_www_form(params) unless params.nil?
  @request = prepare_request(method, body, headers)
  @opts = opts
end

Instance Method Details

#basic_auth(user = nil, password = nil) ⇒ Object



50
51
52
53
54
55
# File 'lib/jpush/utils/http.rb', line 50

def basic_auth(user = nil, password = nil)
  user ||= Config.settings[:app_key]
  password ||= Config.settings[:master_secret]
  @request.basic_auth(user, password)
  self
end

#send_requestObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/jpush/utils/http.rb', line 39

def send_request
  tries ||= DEFAULT_RETRY_TIMES
  opts ||= default_opts.merge @opts
  Net::HTTP.start(@uri.host, @uri.port, opts) do |http|
    http.request(@request)
  end
# if raise Timeout::Error retry it for 3 times
rescue Net::OpenTimeout, Net::ReadTimeout => e
  (tries -= 1).zero? ? (raise Utils::Exceptions::TimeOutError.new(e)) : retry
end