Class: Mihari::HTTP

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, headers: {}, payload: {}) ⇒ HTTP

Returns a new instance of HTTP.



9
10
11
12
13
# File 'lib/mihari/http.rb', line 9

def initialize(url, headers: {}, payload: {})
  @url = url.is_a?(URI) ? url : URI(url.to_s)
  @headers = headers.insensitive
  @payload = payload
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



7
8
9
# File 'lib/mihari/http.rb', line 7

def headers
  @headers
end

#payloadObject (readonly)

Returns the value of attribute payload.



7
8
9
# File 'lib/mihari/http.rb', line 7

def payload
  @payload
end

#urlObject (readonly)

Returns the value of attribute url.



7
8
9
# File 'lib/mihari/http.rb', line 7

def url
  @url
end

Class Method Details

.get(url, headers: {}, params: {}) ⇒ Object



47
48
49
50
# File 'lib/mihari/http.rb', line 47

def get(url, headers: {}, params: {})
  client = new(url, headers: headers, payload: params)
  client.get
end

.post(url, headers: {}, payload: {}) ⇒ Object



52
53
54
55
# File 'lib/mihari/http.rb', line 52

def post(url, headers: {}, payload: {})
  client = new(url, headers: headers, payload: payload)
  client.post
end

Instance Method Details

#getNet::HTTPResponse

Make a GET request

Returns:

  • (Net::HTTPResponse)


20
21
22
23
24
25
26
# File 'lib/mihari/http.rb', line 20

def get
  new_url = url.deep_dup
  new_url.query = Addressable::URI.form_encode(payload) unless payload.empty?

  get = Net::HTTP::Get.new(new_url)
  request get
end

#postNet::HTTPResponse

Make a POST request

Returns:

  • (Net::HTTPResponse)


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

def post
  post = Net::HTTP::Post.new(url)

  case content_type
  when "application/json"
    post.body = JSON.generate(payload)
  when "application/x-www-form-urlencoded"
    post.set_form_data(payload)
  end

  request post
end