Class: Http::POST

Inherits:
Object
  • Object
show all
Defined in:
lib/xhttp/post.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, data = {}, headers = {}) ⇒ POST

Returns a new instance of POST.



12
13
14
15
16
17
18
19
20
21
# File 'lib/xhttp/post.rb', line 12

def initialize(url, data={}, headers={})
  @uri = URI.parse(url)
  @data = data
  @headers = headers

  @response_headers = {}
  @response_content = nil
  @response_status_message = nil
  @response_status_code = nil
end

Instance Method Details

#contentObject



31
32
33
# File 'lib/xhttp/post.rb', line 31

def content
  @response_content
end

#headersObject



35
36
37
# File 'lib/xhttp/post.rb', line 35

def headers
  @response_headers
end

#jsonObject



39
40
41
42
43
44
45
# File 'lib/xhttp/post.rb', line 39

def json
  if @response_headers['content-type'] != 'application/json'
    abort '- Response content is not JSON data'
  end

  JSON.parse(@response_content)
end

#requestObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/xhttp/post.rb', line 47

def request

  @headers['user-agent'] = 'xhttp/0.1.0' if @headers['user-agent'].nil?
  http = Net::HTTP.new(@uri.host, @uri.port)
  req = Net::HTTP::Post.new(@uri.request_uri, @headers)

  unless @data.to_a.empty?
    req.body = @data.to_json
  end

  response = http.request(req)

  @response_status_code = response.code
  @response_status_message = response.message
  @response_content = response.body
  response.each_header do |header|
    @response_headers[header] = response[header]
  end
end

#status_codeObject



23
24
25
# File 'lib/xhttp/post.rb', line 23

def status_code
  @response_status_code
end

#status_messageObject



27
28
29
# File 'lib/xhttp/post.rb', line 27

def status_message
  @response_status_message
end