2

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
secretformula
  • 6,414
  • 3
  • 33
  • 56
sid_com
  • 24,137
  • 26
  • 96
  • 187

3 Answers3

5

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);
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

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.

vstm
  • 12,407
  • 1
  • 51
  • 47
  • Why does my added example not work as I expected (printing the request method)? – sid_com Jul 30 '11 at 16:55
  • 1
    You have to call `add_handler` before any `get` or `post`-method. In your example the handler is added after `get` and thus not called. – vstm Jul 30 '11 at 16:59
1

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.

ErikR
  • 51,541
  • 9
  • 73
  • 124