Class: Struggle::Http

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Http

Returns a new instance of Http.



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

def initialize(url)
  @uri = URI.parse(url)
  @http = Net::HTTP.new(@uri.host, @uri.port)
  @http.use_ssl = true if @uri.scheme == 'https'
  @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



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

def request
  @request
end

#uriObject (readonly)

Returns the value of attribute uri.



6
7
8
# File 'lib/struggle/http.rb', line 6

def uri
  @uri
end

Instance Method Details

#get(params = nil, header = nil) ⇒ Object

get请求,params为携带的参数,header为报文头数据,两个参数都是hash类型,示例http = Struggle::Http.new(“xxx.com/xxx”) result = http.post(‘lily’, age: 18).body



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

def get(params=nil, header=nil)
  @request = Net::HTTP::Get.new(@uri.request_uri, header)
  if !params.blank?
    @request.form_data = params
  end
  @http.request(@request)
end

#post(params = nil, header = nil) ⇒ Object

post请求,params为携带的参数为json类型,header为报文头数据为hash类型,示例:http = Struggle::Http.new(“xxx.com/xxx”) data = ‘lily’, age: 18 result = http.post(data.to_json, => ‘application/json’).body eval(result) => 200, msg: ‘success’



32
33
34
35
36
37
38
# File 'lib/struggle/http.rb', line 32

def post(params=nil, header=nil)
  @request = Net::HTTP::Post.new(@uri.request_uri, header)
  if !params.blank?
    @request.body = params   #post json must body
  end
  @http.request(@request)
end