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 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