LWP::UserAgent - Web user agent class |
LWP::UserAgent - Web user agent class
require LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->timeout(10); $ua->env_proxy; my $response = $ua->get('http://search.cpan.org/'); if ($response->is_success) { print $response->content; # or whatever } else { die $response->status_line; }
The LWP::UserAgent
is a class implementing a web user agent.
LWP::UserAgent
objects can be used to dispatch web requests.
In normal use the application creates an LWP::UserAgent
object, and
then configures it with values for timeouts, proxies, name, etc. It
then creates an instance of HTTP::Request
for the request that
needs to be performed. This request is then passed to one of the
request method the UserAgent, which dispatches it using the relevant
protocol, and returns a HTTP::Response
object. There are
convenience methods for sending the most common request types: get(),
head()
and post(). When using these methods then the creation of the
request object is hidden as shown in the synopsis above.
The basic approach of the library is to use HTTP style communication
for all protocol schemes. This means that you will construct
HTTP::Request
objects and receive HTTP::Response
objects even
for non-HTTP resources like gopher and ftp. In order to achieve
even more similarity to HTTP style communications, gopher menus and
file directories are converted to HTML documents.
The following constructor methods are available:
LWP::UserAgent
object and returns it.
Key/value pair arguments may be provided to set up the initial state.
The following options correspond to attribute methods described below:
KEY DEFAULT ----------- -------------------- agent "libwww-perl/#.##" from undef conn_cache undef cookie_jar undef default_headers HTTP::Headers->new max_size undef max_redirect 7 parse_head 1 protocols_allowed undef protocols_forbidden undef requests_redirectable ['GET', 'HEAD'] timeout 180
The following additional options are also accepted: If the
env_proxy
option is passed in with a TRUE value, then proxy
settings are read from environment variables (see env_proxy()
method
below). If the keep_alive
option is passed in, then a
LWP::ConnCache
is set up (see conn_cache()
method below). The
keep_alive
value is passed on as the total_capacity
for the
connection cache.
The settings of the configuration attributes modify the behaviour of the
LWP::UserAgent
when it dispatches requests. Most of these can also
be initialized by options passed to the constructor method.
The following attributes methods are provided. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value.
_agent()
method (see below).
If the $product_id ends with space then the _agent()
string is
appended to it.
The user agent string should be one or more simple product identifiers with an optional version number separated by the ``/'' character. Examples are:
$ua->agent('Checkbot/0.4 ' . $ua->_agent); $ua->agent('Checkbot/0.4 '); # same as above $ua->agent('Mozilla/5.0'); $ua->agent(""); # don't identify
from
value is send as the ``From'' header in
the requests. Example:
$ua->from('gaas@cpan.org');
The default is to not send a ``From'' header. See the default_headers()
method for the more general interface that allow any header to be defaulted.
extract_cookies($request)
and
add_cookie_header($response)
methods. These methods will then be
invoked by the user agent as requests are sent and responses are
received. Normally this will be a HTTP::Cookies
object or some
subclass.
The default is to have no cookie_jar, i.e. never automatically add ``Cookie'' headers to the requests.
Shortcut: If a reference to a plain hash is passed in as the
$cookie_jar_object, then it is replaced with an instance of
HTTP::Cookies
that is initialized based on the hash. This form also
automatically loads the HTTP::Cookies
module. It means that:
$ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });
is really just a shortcut for:
require HTTP::Cookies; $ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt"));
HTTP::Headers
object. Example:
$ua->default_headers->push_header('Accept-Language' => "no, en");
$ua->default_header('Accept-Language' => "no, en");
LWP::ConnCache
object to use. See the LWP::ConnCache manpage
for details.
get_basic_credentials()
method instead.
The $netloc a string of the form ``<host>:<port>''. The username and password will only be passed to this server. Example:
$ua->credenticals("www.example.com:80", "Some Realm", "foo", "secret");
undef
,
which means that there is no limit. If the returned response content
is only partial, because the size limit was exceeded, then a
``Client-Aborted'' header will be added to the response. The content
might end up longer than max_size
as we abort once appending a
chunk of data makes the length exceed the limit. The ``Content-Length''
header, if present, will indicate the length of the full content and
will normally not be the same as length($res->content)
.
By default, the value is 7. This means that if you call request()
method and the response is a redirect elsewhere which is in turn a
redirect, and so on seven times, then LWP gives up after that seventh
request.
For example: $ua->protocols_allowed( [ 'http', 'https'] );
means that this user agent will allow only those protocols,
and attempts to use this user agent to access URLs with any other
schemes (like ``ftp://...'') will result in a 500 error.
To delete the list, call: $ua->protocols_allowed(undef)
By default, an object has neither a protocols_allowed
list, nor a
protocols_forbidden
list.
Note that having a protocols_allowed
list causes any
protocols_forbidden
list to be ignored.
For example: $ua->protocols_forbidden( [ 'file', 'mailto'] );
means that this user agent will not allow those protocols, and
attempts to use this user agent to access URLs with those schemes
will result in a 500 error.
To delete the list, call: $ua->protocols_forbidden(undef)
$ua->redirect_ok(...)
will allow redirection for. By
default, this is ['GET', 'HEAD']
, as per RFC 2616. To
change to include 'POST', consider:
push @{ $ua->requests_redirectable }, 'POST';
timeout()
value is
180 seconds, i.e. 3 minutes.
The requests is aborted if no activity on the connection to the server
is observed for timeout
seconds. This means that the time it takes
for the complete transaction and the request()
method to actually
return might be longer.
The following methods set up when requests should be passed via a proxy server.
$ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/'); $ua->proxy('gopher', 'http://proxy.sn.no:8001/');
The first form specifies that the URL is to be used for proxying of access methods listed in the list in the first method argument, i.e. 'http' and 'ftp'.
The second form shows a shorthand form for specifying proxy URL for a single access scheme.
$ua->no_proxy('localhost', 'no', ...);
gopher_proxy=http://proxy.my.place/ wais_proxy=http://proxy.my.place/ no_proxy="localhost,my.domain" export gopher_proxy wais_proxy no_proxy
csh or tcsh users should use the setenv
command to define these
environment variables.
On systems with case insensitive environment variables there exists a
name clash between the CGI environment variables and the HTTP_PROXY
environment variable normally picked up by env_proxy(). Because of
this HTTP_PROXY
is not honored for CGI scripts. The
CGI_HTTP_PROXY
environment variable can be used instead.
The methods described in this section are used to dispatch requests via the user agent. The following request methods are provided:
GET
request on the given $url. Further
arguments can be given to initialize the headers of the request. These
are given as separate name/value pairs. The return value is a
response object. See the HTTP::Response manpage for a description of the
interface it provides.
Fields names that start with ``:'' are special. These will not initialize headers of the request but will determine how the response content is treated. The following special field names are recognized:
:content_file => $filename :content_cb => \&callback :read_size_hint => $bytes
If a $filename is provided with the :content_file
option, then the
response content will be saved here instead of in the response
object. If a callback is provided with the :content_cb
option then
this function will be called for each chunk of the response content as
it is received from the server. If neither of these options are
given, then the response content will accumulate in the response
object itself. This might not be suitable for very large response
bodies. Only one of :content_file
or :content_cb
can be
specified. The content of unsuccessful responses will always
accumulate in the response object itself, regardless of the
:content_file
or :content_cb
options passed in.
The :read_size_hint
option is passed to the protocol module which
will try to read data from the server in chunks of this size. A
smaller value for the :read_size_hint
will result in a higher
number of callback invocations.
The callback function is called with 3 arguments: a chunk of data, a
reference to the response object, and a reference to the protocol
object. The callback can abort the request by invoking die(). The
exception message will show up as the ``X-Died'' header field in the
response returned by the get()
function.
HEAD
request on the given $url.
Otherwise it works like the get()
method described above.
POST
request on the given $url, with
%form or @form providing the key/value pairs for the fill-in form
content. Additional headers and content options are the same as for
the get()
method.
This method will use the POST()
function from HTTP::Request::Common
to build the request. See the HTTP::Request::Common manpage for a details on
how to pass form content and other advanced features.
The return value is the the response object.
HTTP::Request
class, but any object with
a similar interface will do. The return value is a response object.
See the HTTP::Request manpage and the HTTP::Response manpage for a description of the
interface provided by these classes.
The request()
method will process redirects and authentication
responses transparently. This means that it may actually send several
simple requests via the simple_request()
method described below.
The request methods described above; get(), head(), post()
and
mirror(), will all dispatch the request they build via this method.
They are convenience methods that simply hides the creation of the
request object for you.
The $content_file, $content_cb and $read_size_hint all correspond to
options described with the get()
method above.
You are allowed to use a CODE reference as content
in the request
object passed in. The content
function should return the content
when called. The content can be returned in chunks. The content
function will be invoked repeatedly until it return an empty string to
signal that there is no more content.
request()
described above.
The difference from request()
is that simple_request()
will not try to
handle redirects or authentication responses. The request()
method
will in fact invoke this method for each simple request it sends.
scheme
. (The scheme
might be a string (like 'http' or
'ftp') or it might be an URI object reference.)
Whether a scheme is supported, is determined by the user agent's
protocols_allowed
or protocols_forbidden
lists (if any), and by
the capabilities of LWP. I.e., this will return TRUE only if LWP
supports this protocol and it's permitted for this particular
object.
The following methods will be invoked as requests are processed. These
methods are documented here because subclasses of LWP::UserAgent
might want to override their behaviour.
The headers affected by the base implementation are; ``User-Agent'', ``From'', ``Range'' and ``Cookie''.
request()
before it tries to follow a
redirection to the request in $response. This should return a TRUE
value if this redirection is permissible. The $prospective_request
will be the request to be sent if this method returns TRUE.
The base implementation will return FALSE unless the method
is in the object's requests_redirectable
list,
FALSE if the proposed redirection is to a ``file://...''
URL, and TRUE otherwise.
request()
to retrieve credentials for documents
protected by Basic or Digest Authentication. The arguments passed in
is the $realm provided by the server, the $uri requested and a boolean
flag to indicate if this is authentication against a proxy server.
The method should return a username and password. It should return an
empty list to abort the authentication resolution attempt. Subclasses
can override this method to prompt the user for the information. An
example of this can be found in lwp-request
program distributed
with this library.
The base implementation simply checks a set of pre-stored member
variables, set up with the credentials()
method.
See the LWP manpage for a complete overview of libwww-perl5. See the lwpcook manpage and the scripts lwp-request and lwp-download for examples of usage.
See the HTTP::Request manpage and the HTTP::Response manpage for a description of the message objects dispatched and received. See the HTTP::Request::Common manpage and the HTML::Form manpage for other ways to build request objects.
See the WWW::Mechanize manpage and the WWW::Search manpage for examples of more
specialized user agents based on LWP::UserAgent
.
Copyright 1995-2008 Gisle Aas.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
LWP::UserAgent - Web user agent class |