|
NAME"Net::Async::HTTP" - use HTTP with "IO::Async"SYNOPSISuse Future::AsyncAwait; use IO::Async::Loop; use Net::Async::HTTP; use URI; my $loop = IO::Async::Loop->new(); my $http = Net::Async::HTTP->new(); $loop->add( $http ); my $response = await $http->do_request( uri => URI->new( "http://www.cpan.org/" ), ); print "Front page of http://www.cpan.org/ is:\n"; print $response->as_string; DESCRIPTIONThis object class implements an asynchronous HTTP user agent. It sends requests to servers, returning Future instances to yield responses when they are received. The object supports multiple concurrent connections to servers, and allows multiple requests in the pipeline to any one connection. Normally, only one such object will be needed per program to support any number of requests.As well as using futures the module also supports a callback-based interface. This module optionally supports SSL connections, if IO::Async::SSL is installed. If so, SSL can be requested either by passing a URI with the "https" scheme, or by passing a true value as the "SSL" parameter. Connection PoolingThere are three ways in which connections to HTTP server hosts are managed by this object, controlled by the value of "max_connections_per_host". This controls when new connections are established to servers, as compared to waiting for existing connections to be free, as new requests are made to them.They are:
These modes all apply per hostname / server port pair; they do not affect the behaviour of connections made to differing hostnames, or differing ports on the same hostname. PARAMETERSThe following named parameters may be passed to "new" or "configure":user_agent => STRINGA string to set in the "User-Agent" HTTP header. If not supplied, one will be constructed that declares "Net::Async::HTTP" and the version number.headers => ARRAY or HASHSince version 0.45.A set of extra headers to apply to every outgoing request. May be specified either as an even-sized array containing key/value pairs, or a hash. Individual header values may be added or changed without replacing the entire set by using the configure method and passing a key called "+headers": $http->configure( +headers => { One_More => "Key" } ); max_redirects => INTOptional. How many levels of redirection to follow. If not supplied, will default to 3. Give 0 to disable redirection entirely.max_in_flight => INTOptional. The maximum number of in-flight requests to allow per host when pipelining is enabled and supported on that host. If more requests are made over this limit they will be queued internally by the object and not sent to the server until responses are received. If not supplied, will default to 4. Give 0 to disable the limit entirely.max_connections_per_host => INTOptional. Controls the maximum number of connections per hostname/server port pair, before requests will be queued awaiting one to be free. Give 0 to disable the limit entirely. See also the "Connection Pooling" section documented above.Currently, if not supplied it will default to 1. However, it has been found in practice that most programs will raise this limit to something higher, perhaps 3 or 4. Therefore, a future version of this module may set a higher value. To test if your application will handle this correctly, you can set a different default by setting an environment variable: $ NET_ASYNC_HTTP_MAXCONNS=3 perl ... timeout => NUMOptional. How long in seconds to wait before giving up on a request. If not supplied then no default will be applied, and no timeout will take place.stall_timeout => NUMOptional. How long in seconds to wait after each write or read of data on a socket, before giving up on a request. This may be more useful than "timeout" on large-file operations, as it will not time out provided that regular progress is still being made.proxy_host => STRINGproxy_port => INTOptional. Default values to apply to each "request" method.cookie_jar => HTTP::CookiesOptional. A reference to a HTTP::Cookies object. Will be used to set cookies in requests and store them from responses.pipeline => BOOLOptional. If false, disables HTTP/1.1-style request pipelining.close_after_request => BOOLSince version 0.45.Optional. If true, will set the "Connection: close" header on outgoing requests and disable pipelining, thus making every request use a new connection. family => INTlocal_host => STRINGlocal_port => INTlocal_addrs => ARRAYlocal_addr => HASH or ARRAYOptional. Parameters to pass on to the "connect" method used to connect sockets to HTTP servers. Sets the socket family and local socket address to "bind()" to. For more detail, see the documentation in IO::Async::Connector.fail_on_error => BOOLOptional. Affects the behaviour of response handling when a "4xx" or "5xx" response code is received. When false, these responses will be processed as other responses and yielded as the result of the future, or passed to the "on_response" callback. When true, such an error response causes the future to fail, or the "on_error" callback to be invoked.The HTTP response and request objects will be passed as well as the code and message, and the failure name will be "http". ( $code_message, "http", $response, $request ) = $f->failure $on_error->( "$code $message", $response, $request ) read_len => INTwrite_len => INTOptional. Used to set the reading and writing buffer lengths on the underlying "IO::Async::Stream" objects that represent connections to the server. If not define, a default of 64 KiB will be used.ip_tos => INT or STRINGOptional. Used to set the "IP_TOS" socket option on client sockets. If given, should either be a "IPTOS_*" constant, or one of the string names "lowdelay", "throughput", "reliability" or "mincost". If undefined or left absent, no option will be set.decode_content => BOOLOptional. If true, incoming responses that have a recognised "Content-Encoding" are handled by the module, and decompressed content is passed to the body handling callback or returned in the "HTTP::Response". See "CONTENT DECODING" below for details of which encoding types are recognised. When this option is enabled, outgoing requests also have the "Accept-Encoding" header added to them if it does not already exist.Currently the default is false, because this behaviour is new, but it may default to true in a later version. Applications which care which behaviour applies should set this to a defined value to ensure it doesn't change. SSL_*Additionally, any parameters whose names start with "SSL_" will be stored and passed on requests to perform SSL requests. This simplifies configuration of common SSL parameters.require_SSL => BOOLOptional. If true, then any attempt to make a request that does not use SSL (either by calling "request", or as a result of a redirection) will immediately fail.SOCKS_*Since version 0.42.Additionally, any parameters whose names start with "SOCKS_" will be stored and used by Net::Async::SOCKS to establish connections via a configured proxy. METHODSThe following methods documented in an "await" expression return Future instances.When returning a Future, the following methods all indicate HTTP-level errors using the Future failure name of "http". If the error relates to a specific response it will be included. The original request is also included. $f->fail( $message, "http", $response, $request ) do_request$response = await $http->do_request( %args ); Send an HTTP request to a server, returning a Future that will yield the response. The request may be represented by an HTTP::Request object, or a URI object, depending on the arguments passed. The following named arguments are used for "HTTP::Request"s:
The following named arguments are used for "URI" requests:
For either request type, it takes the following arguments:
do_request (void)$http->do_request( %args ) When not returning a future, the following extra arguments are used as callbacks instead:
GET, HEAD, PUT, ...$response = await $http->GET( $uri, %args ); $response = await $http->HEAD( $uri, %args ); $response = await $http->PUT( $uri, $content, %args ); $response = await $http->POST( $uri, $content, %args ); $response = await $http->PATCH( $uri, $content, %args ); Convenient wrappers for performing "GET", "HEAD", "PUT", "POST" or "PATCH" requests with a "URI" object and few if any other arguments, returning a "Future". Remember that "POST" with non-form data (as indicated by a plain scalar instead of an "ARRAY" reference of form data name/value pairs) needs a "content_type" key in %args. SUBCLASS METHODSThe following methods are intended as points for subclasses to override, to add extra functionallity.prepare_request$http->prepare_request( $request ) Called just before the "HTTP::Request" object is sent to the server. process_response$http->process_response( $response ) Called after a non-redirect "HTTP::Response" has been received from a server. The originating request will be set in the object. CONTENT DECODINGIf the required decompression modules are installed and available, compressed content can be decoded. If the received "Content-Encoding" is recognised and the required module is available, the content is transparently decoded and the decoded content is returned in the resulting response object, or passed to the data chunk handler. In this case, the original "Content-Encoding" header will be deleted from the response, and its value will be available instead as "X-Original-Content-Encoding".The following content encoding types are recognised by these modules:
Other content encoding types can be registered by calling the following method register_decoderNet::Async::HTTP->register_decoder( $name, $q, $make_decoder ) Registers an encoding type called $name, at the quality value $q. In order to decode this encoding type, $make_decoder will be invoked with no paramters, and expected to return a CODE reference to perform one instance of decoding. $decoder = $make_decoder->() This decoder will be invoked on string buffers to decode them until the end of stream is reached, when it will be invoked with no arguments. $content = $decoder->( $encoded_content ) $content = $decoder->() # EOS EXAMPLESConcurrent GETThe "Future"-returning "GET" method makes it easy to await multiple URLs at once, by using the Future::Utils "fmap_void" utilityuse Future::AsyncAwait; use Future::Utils qw( fmap_void ); my @URLs = ( ... ); my $http = Net::Async::HTTP->new( ... ); $loop->add( $http ); my $future = fmap_void { my ( $url ) = @_; $http->GET( $url ) ->on_done( sub { my $response = shift; say "$url succeeded: ", $response->code; say " Content-Type:", $response->content_type; } ) ->on_fail( sub { my $failure = shift; say "$url failed: $failure"; } ); } foreach => \@URLs, concurrent => 5; await $future; SEE ALSO
SPONSORSParts of this code, or bugfixes to it were paid for by
AUTHORPaul Evans <leonerd@leonerd.org.uk>
Visit the GSP FreeBSD Man Page Interface. |