Methods for building HTTP requests
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 149
149: def encode_auth(k,v)
150: if v.is_a? Array
151: FIELD_ENCODING % [k, ["Basic", Base64.encode64(v.join(":")).chomp].join(" ")]
152: else
153: encode_field(k,v)
154: end
155: end
Encode a field in an HTTP header
# File lib/em-http/client.rb, line 142
142: def encode_field(k, v)
143: FIELD_ENCODING % [k, v]
144: end
# File lib/em-http/client.rb, line 157
157: def encode_headers(head)
158: head.inject('') do |result, (key, value)|
159: # Munge keys from foo-bar-baz to Foo-Bar-Baz
160: key = key.split('-').map { |k| k.to_s.capitalize }.join('-')
161: result << case key
162: when 'Authorization', 'Proxy-authorization'
163: encode_auth(key, value)
164: else
165: encode_field(key, value)
166: end
167: end
168: 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 106
106: def encode_host
107: if @uri.port == 80 || @uri.port == 443
108: return @uri.host
109: else
110: @uri.host + ":#{@uri.port}"
111: end
112: 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 133
133: def encode_param(k, v)
134: if v.is_a?(Array)
135: v.map { |e| escape(k) + "[]=" + escape(e) }.join("&")
136: else
137: escape(k) + "=" + escape(v)
138: end
139: end
# File lib/em-http/client.rb, line 118
118: def encode_query(path, query, uri_query)
119: encoded_query = if query.kind_of?(Hash)
120: query.map { |k, v| encode_param(k, v) }.join('&')
121: else
122: query.to_s
123: end
124: if !uri_query.to_s.empty?
125: encoded_query = [encoded_query, uri_query].reject {|part| part.empty?}.join("&")
126: end
127: return path if encoded_query.to_s.empty?
128: "#{path}?#{encoded_query}"
129: end
# File lib/em-http/client.rb, line 114
114: def encode_request(method, path, query, uri_query)
115: HTTP_REQUEST_HEADER % [method.to_s.upcase, encode_query(path, query, uri_query)]
116: end
Escapes a URI.
# File lib/em-http/client.rb, line 85
85: def escape(s)
86: s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/) {
87: '%'+$1.unpack('H2'*$1.bytesize).join('%').upcase
88: }.tr(' ', '+')
89: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.