开发者

LWP::UserAgent - HTTP::Request

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


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜