Methods for building HTTP requests
# File lib/em-http/client.rb, line 98 def bytesize(string) string.bytesize end
Encode basic auth in an HTTP header In: Array ([user, pass]) - for basic auth
String - custom auth string (OAuth, etc)
# File lib/em-http/client.rb, line 164 def encode_auth(k,v) if v.is_a? Array FIELD_ENCODING % [k, ["Basic", Base64.encode64(v.join(":")).chomp].join(" ")] else encode_field(k,v) end end
Encode a field in an HTTP header
# File lib/em-http/client.rb, line 157 def encode_field(k, v) FIELD_ENCODING % [k, v] end
# File lib/em-http/client.rb, line 172 def encode_headers(head) head.inject('') do |result, (key, value)| # Munge keys from foo-bar-baz to Foo-Bar-Baz key = key.split('-').map { |k| k.to_s.capitalize }.join('-') result << case key when 'Authorization', 'Proxy-authorization' encode_auth(key, value) else encode_field(key, value) end end end
HTTP is kind of retarded that you have to specify a Host header, but if you include port 80 then further redirects will tack on the :80 which is annoying.
# File lib/em-http/client.rb, line 115 def encode_host if @uri.port == 80 || @uri.port == 443 return @uri.host else @uri.host + ":#{@uri.port}" end end
URL encodes query parameters: single k=v, or a URL encoded array, if v is an array of values
# File lib/em-http/client.rb, line 148 def encode_param(k, v) if v.is_a?(Array) v.map { |e| escape(k) + "[]=" + escape(e) }.join("&") else escape(k) + "=" + escape(v) end end
# File lib/em-http/client.rb, line 133 def encode_query(uri, query) encoded_query = if query.kind_of?(Hash) query.map { |k, v| encode_param(k, v) }.join('&') else query.to_s end if !uri.query.to_s.empty? encoded_query = [encoded_query, uri.query].reject {|part| part.empty?}.join("&") end encoded_query.to_s.empty? ? uri.path : "#{uri.path}?#{encoded_query}" end
# File lib/em-http/client.rb, line 123 def encode_request(method, uri, query, proxy) query = encode_query(uri, query) # Non CONNECT proxies require that you provide the full request # uri in request header, as opposed to a relative path. query = uri.join(query) if proxy and not proxy[:use_connect] HTTP_REQUEST_HEADER % [method.to_s.upcase, query] end
Escapes a URI.
# File lib/em-http/client.rb, line 84 def escape(s) s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/) { '%'+$1.unpack('H2'*bytesize($1)).join('%').upcase }.tr(' ', '+') end
Generated with the Darkfish Rdoc Generator 2.