Module: EZHttp

Defined in:
lib/ez_http.rb

Overview

A helper wrapper around net/http, supports http/https(with/without certificate), post/get requests, one method call does everything.

How to use:
 response = EZHttp.Send("https://www.example.com:83/api", "post", {"key1"=>"value1"}, "application/json", nil)
 puts response.body

Author:

Class Method Summary collapse

Class Method Details

.Send(url, method, data, content_type, cert_path) ⇒ Net::HTTPResponse

Send request to specified url and will return responses

Parameters:

  • url: (String)

    to send request to

  • method: (String)

    is “get” or “post”, if nil default is “post”

  • data: (Hash)

    to send

  • content_type: (String)

    if nil default is “application/json”

  • cert_path: (String)

    to the certificate file, set nil if none

Returns:

  • (Net::HTTPResponse)

    response from remote server, example to access its fields: response.body, response.status



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ez_http.rb', line 22

def self.Send(url, method, data, content_type, cert_path)
  # Parse url
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)

  if (url.match(/^https/))
    http.use_ssl = true
  end

  # Create request obj
  request = nil

  method = method || "post"
  case method.downcase
    when "post"
      request = Net::HTTP::Post.new(uri.request_uri)
    when "get"
      request = Net::HTTP::Get.new(uri.request_uri)
    else
      request = Net::HTTP::Post.new(uri.request_uri)
  end

  request.set_form_data(data)
  request["Content-Type"] = content_type || "application/json"

  # Add cert if any
  if (cert_path.nil?)
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  else
    http.use_ssl = true
    pem = File.read(cert_path)
    http.cert = OpenSSL::X509::Certificate.new(pem)
    http.key = OpenSSL::PKey::RSA.new(pem)
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  end

  # Send request and return response
  response = http.request(request)

end