Class: EventMachine::Protocols::HttpClient
Overview
Usage
EventMachine.run {
http = EventMachine::Protocols::HttpClient.request(
:host => server,
:port => 80,
:request => "/index.html",
:query_string => "parm1=value1&parm2=value2"
)
http.callback {|response|
puts response[:status]
puts response[:headers]
puts response[:content]
}
}
– TODO: Add streaming so we can support enormous POSTs. Current max is 20meg. Timeout for connections that run too long or hang somewhere in the middle. Persistent connections (HTTP/1.1), may need a associated delegate object. DNS: Some way to cache DNS lookups for hostnames we connect to. Ruby’s DNS lookups are unbelievably slow. HEAD requests. Chunked transfer encoding. Convenience methods for requests. get, post, url, etc. SSL. Handle status codes like 304, 100, etc. Refactor this code so that protocol errors all get handled one way (an exception?), instead of sprinkling set_deferred_status :failed calls everywhere.
Constant Summary
collapse
- MaxPostContentLength =
20 * 1024 * 1024
Instance Attribute Summary
Attributes inherited from Connection
#signature
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from Deferrable
#callback, #cancel_callback, #cancel_errback, #cancel_timeout, #errback, #fail, future, #set_deferred_status, #succeed, #timeout
Methods inherited from Connection
#associate_callback_target, #close_connection, #close_connection_after_writing, #comm_inactivity_timeout, #comm_inactivity_timeout=, #detach, #error?, #get_outbound_data_size, #get_peer_cert, #get_peername, #get_pid, #get_sock_opt, #get_sockname, #get_status, new, #notify_readable=, #notify_readable?, #notify_writable=, #notify_writable?, #pause, #paused?, #pending_connect_timeout, #pending_connect_timeout=, #proxy_completed, #proxy_incoming_to, #proxy_target_unbound, #reconnect, #resume, #send_data, #send_datagram, #send_file_data, #set_comm_inactivity_timeout, #set_pending_connect_timeout, #ssl_verify_peer, #start_tls, #stop_proxying, #stream_file_data
Constructor Details
Returns a new instance of HttpClient.
75
76
77
|
# File 'lib/em/protocols/httpclient.rb', line 75
def initialize(args)
@args = args
end
|
Class Method Details
.request(args = {}) ⇒ Object
Arg list
:host => ‘ip/dns’, :port => fixnum, :verb => ‘GET’, :request => ‘path’, :basic_auth => => ”, :password => ”, :content => ‘content’, :contenttype => ‘text/plain’, :query_string => ”, :host_header => ”, :cookie => ”, :ssl => false
70
71
72
73
|
# File 'lib/em/protocols/httpclient.rb', line 70
def self.request( args = {} )
args[:port] ||= args[:ssl] ? 443 : 80
EventMachine.connect( args[:host], args[:port], self, args )
end
|
Instance Method Details
#connection_completed ⇒ Object
We send the request when we get a connection. AND, we set an instance variable to indicate we passed through here. That allows #unbind to know whether there was a successful connection. NB: This naive technique won’t work when we have to support multiple requests on a single connection.
91
92
93
94
95
|
# File 'lib/em/protocols/httpclient.rb', line 91
def connection_completed
return if @args[:ssl]
@connected = true
send_request @args
end
|
#dispatch_response ⇒ Object
255
256
257
258
259
260
261
262
263
264
|
# File 'lib/em/protocols/httpclient.rb', line 255
def dispatch_response
@read_state = :base
set_deferred_status :succeeded, {
:content => @content,
:headers => ,
:status => @status
}
close_connection
end
|
#post_init ⇒ Object
79
80
81
82
83
84
|
# File 'lib/em/protocols/httpclient.rb', line 79
def post_init
start_tls if @args[:ssl]
@start_time = Time.now
@data = ""
@read_state = :base
end
|
#receive_data(data) ⇒ Object
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
|
# File 'lib/em/protocols/httpclient.rb', line 174
def receive_data data
while data and data.length > 0
case @read_state
when :base
@data = ""
= []
@content_length = nil
@content = ""
@status = nil
@read_state = :header
@connection_close = nil
when :header
ary = data.split( /\r?\n/m, 2 )
if ary.length == 2
data = ary.last
if ary.first == ""
if (@content_length and @content_length > 0) || @connection_close
@read_state = :content
else
dispatch_response
@read_state = :base
end
else
<< ary.first
if .length == 1
parse_response_line
elsif ary.first =~ /\Acontent-length:\s*/i
@content_length ||= $'.to_i
elsif ary.first =~ /\Aconnection:\s*close/i
@connection_close = true
end
end
else
@data << data
data = ""
end
when :content
if @content_length
bytes_needed = @content_length - @content.length
@content += data[0, bytes_needed]
data = data[bytes_needed..-1] || ""
if @content_length == @content.length
dispatch_response
@read_state = :base
end
else
@content << data
data = ""
end
end
end
end
|
#send_request(args) ⇒ Object
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
|
# File 'lib/em/protocols/httpclient.rb', line 102
def send_request args
args[:verb] ||= args[:method]
args[:verb] ||= :get
verb = args[:verb].to_s.upcase
unless ["GET", "POST", "PUT", "DELETE", "HEAD"].include?(verb)
set_deferred_status :failed, {:status => 0}
return
end
request = args[:request] || "/"
unless request[0,1] == "/"
request = "/" + request
end
qs = args[:query_string] || ""
if qs.length > 0 and qs[0,1] != '?'
qs = "?" + qs
end
version = args[:version] || "1.1"
host = args[:host_header] || args[:host] || "_"
port = args[:port]
postcontenttype = args[:contenttype] || "application/octet-stream"
postcontent = args[:content] || ""
raise "oversized content in HTTP POST" if postcontent.length > MaxPostContentLength
req = [
"#{verb} #{request}#{qs} HTTP/#{version}",
"Host: #{host}:#{port}",
"User-agent: Ruby EventMachine",
]
if verb == "POST" || verb == "PUT"
req << "Content-type: #{postcontenttype}"
req << "Content-length: #{postcontent.length}"
end
if args[:cookie]
req << "Cookie: #{args[:cookie]}"
end
args[:custom_headers].each do |k,v|
req << "#{k}: #{v}"
end if args[:custom_headers]
if args[:basic_auth]
basic_auth_string = ["#{args[:basic_auth][:username]}:#{args[:basic_auth][:password]}"].pack('m').strip.gsub(/\n/,'')
req << "Authorization: Basic #{basic_auth_string}"
end
req << ""
reqstring = req.map {|l| "#{l}\r\n"}.join
send_data reqstring
if verb == "POST" || verb == "PUT"
send_data postcontent
end
end
|
#ssl_handshake_completed ⇒ Object
97
98
99
100
|
# File 'lib/em/protocols/httpclient.rb', line 97
def ssl_handshake_completed
@connected = true
send_request @args
end
|
#unbind ⇒ Object
266
267
268
269
270
271
272
|
# File 'lib/em/protocols/httpclient.rb', line 266
def unbind
if !@connected
set_deferred_status :failed, {:status => 0}
elsif (@read_state == :content and @content_length == nil)
dispatch_response
end
end
|