If I do this
#!/usr/local/bin/perl
use warnings;
use 5.014;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new();
my $res = $ua->get( 'http://www.perl.org' );
I can call HTTP::Response
methods like this
say $res->code;
Is it somehow possible to call HTTP::Request
methods from the $res
object or needs that the creation of a HTTP::Request
object explicitly?
my $ua = LWP::UserAgent->new();
my $method;
my $res = $ua->get( 'http://www.perl.org' );
$ua->add_handler( request_prepare => sub { my( $request, $ua, $h ) = @_; $method = $request->method; }, );
say $method; # Use of uninitialized value $method in say
The HTTP::Request
is used internally by LWP::UserAgent
and if they would return it via get
or post
-Methods it would already be too late since the request is already done. But they have apparently foreseen the need for accessing the request object so they implemented callbacks so you can modify the request before it is sent:
$ua->add_handler(request_prepare => sub {
my($request, $ua, $h) = @_;
# $request is a HTPP::Request
$request->header("X-Reason" => "just checkin");
});
So if you need to access the request-object without creating it and setting it up - callbacks are the way to go.