简体   繁体   中英

LWP::UserAgent and HTTP::Request for a POST request

In a certain script I tried to write this:

my $ua = LWP::UserAgent->new;
my $res = $ua->post($url, Content => $data);

and got "400 Bad Request". After some reading I tried this:

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( 'POST', $url );
$req->content( $data );
my $res = $ua->request( $req );

and it worked, but I thought these two should do the same. What am I missing here? Am I misunderstanding something in the documentation of HTTP::Request and LWP::UserAgent ?

Is there a way to ask LWP::UserAgent to print what it is doing?

Here's one way to do it:

#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;

{
    no strict "refs";
    no warnings "redefine";
    my $orig_sub = \&LWP::UserAgent::send_request;
    *{"LWP::UserAgent::send_request"} = sub {
        my ($self, $request) = @_;
        print $request->as_string . "\n";
        my $response = $orig_sub->(@_);
        print $response->as_string . "\n";
        return $response;
    };
}

my $a = LWP::UserAgent->new;
my $response = $a->get("http://google.com");

It will print out all the requests and responses that LWP::UserAgent does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM