Method: HttpSession#request

Defined in:
lib/http_session.rb

#request(uri = '/', headers = {}, type = :get, post_params = {}, redirect_limit = @@redirect_limit, retry_limit = @@retry_limit) ⇒ Object

internally handle GET and POST requests (recursively for redirects and retries) returns Net::HTTPResponse, or raises Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, EOFError, Net::ProtocolError



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/http_session.rb', line 72

def request(uri='/', headers={}, type=:get, post_params={}, redirect_limit=@@redirect_limit, retry_limit=@@retry_limit)
  req = case type
    when :get
      Net::HTTP::Get.new(uri)
    when :post
      Net::HTTP::Post.new(uri)
    else
      raise ArgumentError, "bad type: #{type}"
  end
  headers.each { |k, v| req[k] = v } unless headers.empty?
  req['Cookie'] = cookie_string if cookies?
  req.set_form_data(post_params) if type == :post
  
  begin
    handle.start unless handle.started? # may raise Timeout::Error or OpenSSL::SSL::SSLError
    response = handle.request(req) # may raise Errno::* (subclasses of SystemCallError) or EOFError
  rescue Timeout::Error, SystemCallError, EOFError
    handle.finish if handle.started?
    raise if retry_limit == 0
    request(uri, headers, type, post_params, redirect_limit, retry_limit - 1)
    
  else
    add_cookies response
    if response.kind_of?(Net::HTTPRedirection)
      raise Net::HTTPError.new('Redirection limit exceeded', response)  if redirect_limit == 0
      loc = URI.parse(response['location'])
      if loc.scheme && loc.host && loc.port
        self.class.use(loc.host, loc.scheme == 'https', loc.port).request(loc.path + (loc.query.nil? ? '' : "?#{loc.query}"), headers, :get, {}, redirect_limit - 1)
      else
        # only really bad web servers would ever send this... since it's not technically a valid value!
        request(loc.path + (loc.query.nil? ? '' : "?#{loc.query}"), headers, :get, {}, redirect_limit - 1)
      end
    else
      response.error! unless response.kind_of?(Net::HTTPOK) # raises Net::HTTP*Error/Exception (subclasses of Net::ProtocolError)
      raise Net::HTTPError.new('Document has no body', response) if response.body.nil? || response.body == ''
      response
    end
  end
end