2
votes

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
3

3 Answers

5
votes

To get the request object that was created for you:

my $response = $ua->get('http://www.example.com/');
my $request = ($response->redirects, $response)[0]->request;

Might be easier just to create a request object yourself

use HTTP::Request::Common qw( GET );
my $request = GET('http://www.example.com/');
my $response = $ua->request($request);
2
votes

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.

1
votes

Which HTTP::Request methods do you want to call? And on which request object? The last request made by $ua?

As far as I can tell, LWP::get does not save the last request created/sent anywhere.