1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
require 'json'
require 'net/http'
require 'net/https'
require 'uri'
require 'openssl'
class HttpClient
attr_accessor :uri
attr_accessor :header
attr_accessor :cookies
attr_accessor :body
attr_accessor :response
attr_accessor :response_code
@@req_xml = <<EOF
<?xml version="1.0"?>
<a:propfind xmlns:a="DAV:">
<a:prop><a:resourcetype/></a:prop>
</a:propfind>
EOF
def initialize(url: nil, username: nil, password: nil, headers: Hash.new, cookies: Hash.new, body: nil)
@uri = URI.parse(url)
@username = username
@password = password
@headers = headers
@cookies = cookies
@body = body
end
def do_http(method: :get, do_cookies_p: false, read_timeout: 600, extra_headers: Hash.new)
resp = nil
http = Net::HTTP.new(@uri.host, @uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http.read_timeout = read_timeout
req = case method
when :get
Net::HTTP::Get.new(uri.request_uri, @headers.merge(extra_headers))
when :delete
Net::HTTP::Delete.new(uri.request_uri, @headers.merge(extra_headers))
when :post
Net::HTTP::Post.new(uri.request_uri, @headers.merge(extra_headers))
when :put
Net::HTTP::Put.new(uri.request_uri, @headers.merge(extra_headers))
when :propfind
Net::HTTP::Propfind.new(uri.request_uri, {"Depth" => "1"})
end
req.basic_auth(@username, @password) if @username and @password
if method == :propfind
req.body = @@req_xml
else
req.body = @body if @body
end
resp = http.request(req)
@response = resp.body
@response_code = resp.class
get_cookies(resp) if do_cookies_p
end
# Below is a pair of example Set-Cookie headers after
# Net::HttpClient turns them into a concatenated string. Note the
# bad use of a comma to separate the cookies. It's bad because a
# comma already appears in the date. We deal with that by eating
# the date with gsub() before splitting.
#
# csrftoken=urvsX10TfzWIK1fgctZ2HjHuNQZDr3E7; expires=Wed, 16-Nov-2016 16:57:20 GMT; Max-Age=31449600; Path=/, sessionid=e0t7304jn44ssc7gw412abup4aasehgb; expires=Wed, 18-Nov-2015 17:57:20 GMT; httponly; Max-Age=3600; Path=/
#
# rememberMe=deleteMe; Path=/Openbook; Max-Age=0; Expires=Wed, 16-Dec-2015 22:53:58 GMT
def get_cookies(resp)
if resp.response['Set-Cookie']
rawstring = resp.response['Set-Cookie'].gsub(/expires.*?Path=/, '')
rawstring.chomp.split(",").each do |entry|
entryparts = entry.split(";")
if entryparts.length >= 1
cookieparts = entryparts[0].split("=")
name = cookieparts[0].strip
value = cookieparts[1].strip
@cookies[name] = value
end
end
end
end
def create_cookie(name, value)
"#{name}=#{value}; Path=/"
end
end
|