I've uploaded libwww-perl 5.815 to CPAN.

The main change this time is the introduction of handlers to drive the
processing of requests in LWP::UserAgent.  You can also register your
own handlers for modifying and processing requests or responses on
their way, which I think is a much more flexible approach that trying
to subclass LWP::UserAgent to customize it.  If we have had these
early on then the LWP::UserAgent API could have been so much simpler
as the effect of most current attributes can easily be set up with
trivial handlers.  Also thanks to contributions by Bron Gondwana LWP's
Basic/Digest authenticate modules now registers handlers which allow
them to automatically fill in the Authorization headers without first
taking the roundtrip of a 401 response when LWP knows the credentials
for a given realm.

This code shows some examples of what you can use custom handlers for:

#!perl

use LWP::UserAgent;
$ua = LWP::UserAgent->new;

# example of handler to add custom headers
$ua->add_handler("request_prepare", sub {
    my $req = shift;
    $req->init_header("Accept-Language" => ["no", "en-US"]);
});

# example of handler to rewrite the method for certain requests
$ua->add_handler("request_prepare",
    sub {
        my $req = shift;
        $req->method("TRACE");
    },
    m_scheme => "http",
    m_method => "GET",
    m_domain => "example.com",
);

# example of handler to monitor the requests that are sent
$ua->add_handler("request_send", sub {
    my $req = shift;
    print $req->as_string;
    return;
});

# example of handler that only pass HTTP requests through
$ua->add_handler("request_send", sub {
    my $req = shift;
    return if $req->uri->scheme =~ /^http/;
    return HTTP::Response->new(403, undef,
        ["Server" => $ua->agent, "Content-Type" => "text/plain"],
        "It's our brand new policy to restrict access to HTTP!\n"
    );
});

# example of handler that counts number how much data we receive
my $bytes_received = 0;
$ua->add_handler("response_data", sub {
    $bytes_received += length($_[3]);
});

print $ua->get("http://www.example.com";)->as_string;
print $ua->get("ftp://ftp.example.com";)->as_string;

print "$bytes_received bytes of content received (not including
protocol overhead)\n";

__END__

Enjoy!

--Gisle

Reply via email to