16
17
18
19
20
21
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
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/nifty/utils/http.rb', line 16
def self.request(method, url, options = {})
options[:headers] ||= {}
uri = URI.parse(url)
request = method.new(uri.path.length == 0 ? "/" : uri.path)
options[:headers].each { |k,v| request.add_field k, v }
if options[:username]
request.basic_auth(options[:username], options[:password])
end
if options[:params].is_a?(Hash)
request.set_form_data(options[:params])
elsif options[:json].is_a?(String)
request.add_field 'Content-Type', 'application/json'
request.body = options[:json]
end
if options[:user_agent]
request['User-Agent'] = options[:user_agent]
end
connection = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
connection.use_ssl = true
connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
begin
timeout = options[:timeout] || 60
Timeout.timeout(timeout) do
result = connection.request(request)
if result.content_type == 'application/json'
body = JSON.parse(result.body)
else
body = result.body
end
{
:code => result.code.to_i,
:type => result.content_type,
:body => body
}
end
rescue SocketError, Errno::ECONNRESET, EOFError, Errno::EINVAL => e
{
:code => -2,
:body => e.message
}
rescue Timeout::Error => e
{
:code => -1,
:body => "Timed out after #{timeout}s"
}
end
end
|