1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 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 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 172 173 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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
|
# NAME
POE::Component::Client::HTTP - a HTTP user-agent component
# VERSION
version 0.947
# SYNOPSIS
use POE qw(Component::Client::HTTP);
POE::Component::Client::HTTP->spawn(
Agent => 'SpiffCrawler/0.90', # defaults to something long
Alias => 'ua', # defaults to 'weeble'
From => 'spiffster@perl.org', # defaults to undef (no header)
Protocol => 'HTTP/0.9', # defaults to 'HTTP/1.1'
Timeout => 60, # defaults to 180 seconds
MaxSize => 16384, # defaults to entire response
Streaming => 4096, # defaults to 0 (off)
FollowRedirects => 2, # defaults to 0 (off)
Proxy => "http://localhost:80", # defaults to HTTP_PROXY env. variable
NoProxy => [ "localhost", "127.0.0.1" ], # defs to NO_PROXY env. variable
BindAddr => "12.34.56.78", # defaults to INADDR_ANY
);
$kernel->post(
'ua', # posts to the 'ua' alias
'request', # posts to ua's 'request' state
'response', # which of our states will receive the response
$request, # an HTTP::Request object
);
# This is the sub which is called when the session receives a
# 'response' event.
sub response_handler {
my ($request_packet, $response_packet) = @_[ARG0, ARG1];
# HTTP::Request
my $request_object = $request_packet->[0];
# HTTP::Response
my $response_object = $response_packet->[0];
my $stream_chunk;
if (! defined($response_object->content)) {
$stream_chunk = $response_packet->[1];
}
print(
"*" x 78, "\n",
"*** my request:\n",
"-" x 78, "\n",
$request_object->as_string(),
"*" x 78, "\n",
"*** their response:\n",
"-" x 78, "\n",
$response_object->as_string(),
);
if (defined $stream_chunk) {
print "-" x 40, "\n", $stream_chunk, "\n";
}
print "*" x 78, "\n";
}
# DESCRIPTION
POE::Component::Client::HTTP is an HTTP user-agent for POE. It lets
other sessions run while HTTP transactions are being processed, and it
lets several HTTP transactions be processed in parallel.
It supports keep-alive through POE::Component::Client::Keepalive,
which in turn uses POE::Component::Resolver for asynchronous IPv4 and
IPv6 name resolution.
HTTP client components are not proper objects. Instead of being
created, as most objects are, they are "spawned" as separate sessions.
To avoid confusion (and hopefully not cause other confusion), they
must be spawned with a `spawn` method, not created anew with a `new`
one.
# CONSTRUCTOR
## spawn
PoCo::Client::HTTP's `spawn` method takes a few named parameters:
- Agent => $user_agent_string
- Agent => \@list_of_agents
If a UserAgent header is not present in the HTTP::Request, a random
one will be used from those specified by the `Agent` parameter. If
none are supplied, POE::Component::Client::HTTP will advertise itself
to the server.
`Agent` may contain a reference to a list of user agents. If this is
the case, PoCo::Client::HTTP will choose one of them at random for
each request.
- Alias => $session_alias
`Alias` sets the name by which the session will be known. If no
alias is given, the component defaults to "weeble". The alias lets
several sessions interact with HTTP components without keeping (or
even knowing) hard references to them. It's possible to spawn several
HTTP components with different names.
- ConnectionManager => $poco_client_keepalive
`ConnectionManager` sets this component's connection pool manager.
It expects the connection manager to be a reference to a
POE::Component::Client::Keepalive object. The HTTP client component
will call `allocate()` on the connection manager itself so you should
not have done this already.
my $pool = POE::Component::Client::Keepalive->new(
keep_alive => 10, # seconds to keep connections alive
max_open => 100, # max concurrent connections - total
max_per_host => 20, # max concurrent connections - per host
timeout => 30, # max time (seconds) to establish a new connection
);
POE::Component::Client::HTTP->spawn(
# ...
ConnectionManager => $pool,
# ...
);
See [POE::Component::Client::Keepalive](http://search.cpan.org/perldoc?POE::Component::Client::Keepalive) for more information,
including how to alter the connection manager's resolver
configuration (for example, to force IPv6 or prefer it before IPv4).
- CookieJar => $cookie_jar
`CookieJar` sets the component's cookie jar. It expects the cookie
jar to be a reference to a HTTP::Cookies object.
- From => $admin_address
`From` holds an e-mail address where the client's administrator
and/or maintainer may be reached. It defaults to undef, which means
no From header will be included in requests.
- MaxSize => OCTETS
`MaxSize` specifies the largest response to accept from a server.
The content of larger responses will be truncated to OCTET octets.
This has been used to return the <head></head> section of web pages
without the need to wade through <body></body>.
- NoProxy => [ $host_1, $host_2, ..., $host_N ]
- NoProxy => "host1,host2,hostN"
`NoProxy` specifies a list of server hosts that will not be proxied.
It is useful for local hosts and hosts that do not properly support
proxying. If NoProxy is not specified, a list will be taken from the
NO_PROXY environment variable.
NoProxy => [ "localhost", "127.0.0.1" ],
NoProxy => "localhost,127.0.0.1",
- BindAddr => $local_ip
Specify `BindAddr` to bind all client sockets to a particular local
address. The value of BindAddr will be passed through
POE::Component::Client::Keepalive to POE::Wheel::SocketFactory (as
`bind_address`). See that module's documentation for implementation
details.
BindAddr => "12.34.56.78"
- Protocol => $http_protocol_string
`Protocol` advertises the protocol that the client wishes to see.
Under normal circumstances, it should be left to its default value:
"HTTP/1.1".
- Proxy => [ $proxy_host, $proxy_port ]
- Proxy => $proxy_url
- Proxy => $proxy_url,$proxy_url,...
`Proxy` specifies one or more proxy hosts that requests will be
passed through. If not specified, proxy servers will be taken from
the HTTP_PROXY (or http_proxy) environment variable. No proxying will
occur unless Proxy is set or one of the environment variables exists.
The proxy can be specified either as a host and port, or as one or
more URLs. Proxy URLs must specify the proxy port, even if it is 80.
Proxy => [ "127.0.0.1", 80 ],
Proxy => "http://127.0.0.1:80/",
`Proxy` may specify multiple proxies separated by commas.
PoCo::Client::HTTP will choose proxies from this list at random. This
is useful for load balancing requests through multiple gateways.
Proxy => "http://127.0.0.1:80/,http://127.0.0.1:81/",
- Streaming => OCTETS
`Streaming` changes allows Client::HTTP to return large content in
chunks (of OCTETS octets each) rather than combine the entire content
into a single HTTP::Response object.
By default, Client::HTTP reads the entire content for a response into
memory before returning an HTTP::Response object. This is obviously
bad for applications like streaming MP3 clients, because they often
fetch songs that never end. Yes, they go on and on, my friend.
When `Streaming` is set to nonzero, however, the response handler
receives chunks of up to OCTETS octets apiece. The response handler
accepts slightly different parameters in this case. ARG0 is also an
HTTP::Response object but it does not contain response content,
and ARG1 contains a a chunk of raw response
content, or undef if the stream has ended.
sub streaming_response_handler {
my $response_packet = $_[ARG1];
my ($response, $data) = @$response_packet;
print SAVED_STREAM $data if defined $data;
}
- FollowRedirects => $number_of_hops_to_follow
`FollowRedirects` specifies how many redirects (e.g. 302 Moved) to
follow. If not specified defaults to 0, and thus no redirection is
followed. This maintains compatibility with the previous behavior,
which was not to follow redirects at all.
If redirects are followed, a response chain should be built, and can
be accessed through $response_object->previous(). See HTTP::Response
for details here.
- Timeout => $query_timeout
`Timeout` sets how long POE::Component::Client::HTTP has to process
an application's request, in seconds. `Timeout` defaults to 180
(three minutes) if not specified.
It's important to note that the timeout begins when the component
receives an application's request, not when it attempts to connect to
the web server.
Timeouts may result from sending the component too many requests at
once. Each request would need to be received and tracked in order.
Consider this:
$_[KERNEL]->post(component => request => ...) for (1..15_000);
15,000 requests are queued together in one enormous bolus. The
component would receive and initialize them in order. The first
socket activity wouldn't arrive until the 15,000th request was set up.
If that took longer than `Timeout`, then the requests that have
waited too long would fail.
`ConnectionManager`'s own timeout and concurrency limits also affect
how many requests may be processed at once. For example, most of the
15,000 requests would wait in the connection manager's pool until
sockets become available. Meanwhile, the `Timeout` would be counting
down.
Applications may elect to control concurrency outside the component's
`Timeout`. They may do so in a few ways.
The easiest way is to limit the initial number of requests to
something more manageable. As responses arrive, the application
should handle them and start new requests. This limits concurrency to
the initial request count.
An application may also outsource job throttling to another module,
such as POE::Component::JobQueue.
In any case, `Timeout` and `ConnectionManager` may be tuned to
maximize timeouts and concurrency limits. This may help in some
cases. Developers should be aware that doing so will increase memory
usage. POE::Component::Client::HTTP and KeepAlive track requests in
memory, while applications are free to keep pending requests on disk.
# ACCEPTED EVENTS
Sessions communicate asynchronously with PoCo::Client::HTTP. They
post requests to it, and it posts responses back.
## request
Requests are posted to the component's "request" state. They include
an HTTP::Request object which defines the request. For example:
$kernel->post(
'ua', 'request', # http session alias & state
'response', # my state to receive responses
GET 'http://poe.perl.org', # a simple HTTP request
'unique id', # a tag to identify the request
'progress', # an event to indicate progress
'http://1.2.3.4:80/' # proxy to use for this request
);
Requests include the state to which responses will be posted. In the
previous example, the handler for a 'response' state will be called
with each HTTP response. The "progress" handler is optional and if
installed, the component will provide progress metrics (see sample
handler below). The "proxy" parameter is optional and if not defined,
a default proxy will be used if configured. No proxy will be used if
neither a default one nor a "proxy" parameter is defined.
## pending_requests_count
There's also a pending_requests_count state that returns the number of
requests currently being processed. To receive the return value, it
must be invoked with $kernel->call().
my $count = $kernel->call('ua' => 'pending_requests_count');
NOTE: Sometimes the count might not be what you expected, because responses
are currently in POE's queue and you haven't processed them. This could happen
if you configure the `ConnectionManager`'s concurrency to a high enough value.
## cancel
Cancel a specific HTTP request. Requires a reference to the original
request (blessed or stringified) so it knows which one to cancel. See
L<progress handler> below for notes on canceling streaming requests.
To cancel a request based on its blessed HTTP::Request object:
$kernel->post( component => cancel => $http_request );
To cancel a request based on its stringified HTTP::Request object:
$kernel->post( component => cancel => "$http_request" );
## shutdown
Responds to all pending requests with 408 (request timeout), and then
shuts down the component and all subcomponents.
# SENT EVENTS
## response handler
In addition to all the usual POE parameters, HTTP responses come with
two list references:
my ($request_packet, $response_packet) = @_[ARG0, ARG1];
`$request_packet` contains a reference to the original HTTP::Request
object. This is useful for matching responses back to the requests
that generated them.
my $http_request_object = $request_packet->[0];
my $http_request_tag = $request_packet->[1]; # from the 'request' post
`$response_packet` contains a reference to the resulting
HTTP::Response object.
my $http_response_object = $response_packet->[0];
Please see the HTTP::Request and HTTP::Response manpages for more
information.
## progress handler
The example progress handler shows how to calculate a percentage of
download completion.
sub progress_handler {
my $gen_args = $_[ARG0]; # args passed to all calls
my $call_args = $_[ARG1]; # args specific to the call
my $req = $gen_args->[0]; # HTTP::Request object being serviced
my $tag = $gen_args->[1]; # Request ID tag from.
my $got = $call_args->[0]; # Number of bytes retrieved so far.
my $tot = $call_args->[1]; # Total bytes to be retrieved.
my $oct = $call_args->[2]; # Chunk of raw octets received this time.
my $percent = $got / $tot * 100;
printf(
"-- %.0f%% [%d/%d]: %s\n", $percent, $got, $tot, $req->uri()
);
# To cancel the request:
# $_[KERNEL]->post( component => cancel => $req );
}
### DEPRECATION WARNING
The third return argument (the raw octets received) has been deprecated.
Instead of it, use the Streaming parameter to get chunks of content
in the response handler.
# REQUEST CALLBACKS
The HTTP::Request object passed to the request event can contain a
CODE reference as `content`. This allows for sending large files
without wasting memory. Your callback should return a chunk of data
each time it is called, and an empty string when done. Don't forget
to set the Content-Length header correctly. Example:
my $request = HTTP::Request->new( PUT => 'http://...' );
my $file = '/path/to/large_file';
open my $fh, '<', $file;
my $upload_cb = sub {
if ( sysread $fh, my $buf, 4096 ) {
return $buf;
}
else {
close $fh;
return '';
}
};
$request->content_length( -s $file );
$request->content( $upload_cb );
$kernel->post( ua => request, 'response', $request );
# CONTENT ENCODING AND COMPRESSION
Transparent content decoding has been disabled as of version 0.84.
This also removes support for transparent gzip requesting and
decompression.
To re-enable gzip compression, specify the gzip Content-Encoding and
use HTTP::Response's decoded_content() method rather than content():
my $request = HTTP::Request->new(
GET => "http://www.yahoo.com/", [
'Accept-Encoding' => 'gzip'
]
);
# ... time passes ...
my $content = $response->decoded_content();
The change in POE::Component::Client::HTTP behavior was prompted by
changes in HTTP::Response that surfaced a bug in the component's
transparent gzip handling.
Allowing the application to specify and handle content encodings seems
to be the most reliable and flexible resolution.
For more information about the problem and discussions regarding the
solution, see:
[http://www.perlmonks.org/?node_id=683833](http://www.perlmonks.org/?node_id=683833) and
[http://rt.cpan.org/Ticket/Display.html?id=35538](http://rt.cpan.org/Ticket/Display.html?id=35538)
# CLIENT HEADERS
POE::Component::Client::HTTP sets its own response headers with
additional information. All of its headers begin with "X-PCCH".
## X-PCCH-Errmsg
POE::Component::Client::HTTP may fail because of an internal client
error rather than an HTTP protocol error. X-PCCH-Errmsg will contain a
human readable reason for client failures, should they occur.
The text of X-PCCH-Errmsg may also be repeated in the response's
content.
## X-PCCH-Peer
X-PCCH-Peer contains the remote IPv4 address and port, separated by a
period. For example, "127.0.0.1.8675" represents port 8675 on
localhost.
Proxying will render X-PCCH-Peer nearly useless, since the socket will
be connected to a proxy rather than the server itself.
This feature was added at Doreen Grey's request. Doreen wanted a
means to find the remote server's address without having to make an
additional request.
# ENVIRONMENT
POE::Component::Client::HTTP uses two standard environment variables:
HTTP_PROXY and NO_PROXY.
HTTP_PROXY sets the proxy server that Client::HTTP will forward
requests through. NO_PROXY sets a list of hosts that will not be
forwarded through a proxy.
See the Proxy and NoProxy constructor parameters for more information
about these variables.
# SEE ALSO
This component is built upon HTTP::Request, HTTP::Response, and POE.
Please see its source code and the documentation for its foundation
modules to learn more. If you want to use cookies, you'll need to
read about HTTP::Cookies as well.
Also see the test program, t/01_request.t, in the PoCo::Client::HTTP
distribution.
# BUGS
There is no support for CGI_PROXY or CgiProxy.
Secure HTTP (https) proxying is not supported at this time.
There is no object oriented interface. See
[POE::Component::Client::Keepalive](http://search.cpan.org/perldoc?POE::Component::Client::Keepalive) and
[POE::Component::Resolver](http://search.cpan.org/perldoc?POE::Component::Resolver) for examples of a decent OO interface.
# AUTHOR, COPYRIGHT, & LICENSE
POE::Component::Client::HTTP is
-
Copyright 1999-2009 Rocco Caputo
-
Copyright 2004 Rob Bloodgood
-
Copyright 2004-2005 Martijn van Beers
All rights are reserved. POE::Component::Client::HTTP is free
software; you may redistribute it and/or modify it under the same
terms as Perl itself.
# CONTRIBUTORS
Joel Bernstein solved some nasty race conditions. Portugal Telecom
[http://www.sapo.pt/](http://www.sapo.pt/) was kind enough to support his contributions.
Jeff Bisbee added POD tests and documentation to pass several of them
to version 0.79. He's a kwalitee-increasing machine!
# BUG TRACKER
https://rt.cpan.org/Dist/Display.html?Queue=POE-Component-Client-HTTP
# REPOSITORY
Github: [http://github.com/rcaputo/poe-component-client-http](http://github.com/rcaputo/poe-component-client-http) .
Gitorious: [http://gitorious.org/poe-component-client-http](http://gitorious.org/poe-component-client-http) .
# OTHER RESOURCES
[http://search.cpan.org/dist/POE-Component-Client-HTTP/](http://search.cpan.org/dist/POE-Component-Client-HTTP/)
|