require 'net/http' require 'cgi' module WebSpeak class Request attr_reader :cookies, :headers, :params, :query_params attr_accessor :host, :port, :path, :verbose, :response def initialize(host="localhost", port=80, path="/") @host = host @port = port @path = path self.verbose = false @cookies = {} @query_params = {} @params = {} @headers = {} end def post log_hash(params, "PARAMS") if self.verbose log_hash(query_params, "QUERY_PARAMS") if self.verbose add_cookies_to_header log_hash(headers, "HEADERS") if self.verbose @path_with_params = "#{@path}" @path_with_params += "?#{to_param_string(query_params)}" unless query_params.empty? Net::HTTP.start(@host, @port) do |http| puts "Posting to http://#{@host}:#{@port}#{@path_with_params}" if self.verbose @response = http.post(@path_with_params, to_param_string(params), headers) end end def get add_cookies_to_header @path_with_params = "#{@path}" sep = "?" unless query_params.empty? @path_with_params += "#{sep}#{to_param_string(query_params)}" sep = "&" end @path_with_params += "#{sep}#{to_param_string(params)}" unless params.empty? Net::HTTP.start(@host, @port) do |http| puts "Getting http://#{@host}:#{@port}#{@path_with_params}" if self.verbose @response = http.get(@path_with_params, headers) end end private def add_cookies_to_header if @cookies.size > 0 cookie_header = "" @cookies.each do |k,v| cookie_header += k + "=" + v + "; " end headers['Cookie'] = cookie_header end end def escape(str); CGI::escape(str); end def to_param_string(hsh) (hsh.collect {|k,v| escape(k.to_s) + '=' + escape(v.to_s)}).join('&') end def log_hash(hsh, name) puts "===== #{name} =====" hsh.sort.each do |k,v| puts " #{k}=#{v}" end puts "======#{"=" * name.size}======" end end end