3

我尝试使用HTTP::Request::Common向 URL 发布帖子。不幸的是,它似乎不适用于身份验证,我不得不切换回普通的 ol' HTTP::Request。如果我不需要身份验证,我可以这样完成整个事情:

use HTTP::Request::Common;

my $browser = LWP::UserAgent->new;

$browser->request (
    POST $url, 
    Content => [
        Name => $name,
        Address => $address,
    ],
);

不幸的是,由于身份验证,我不得不回退到HTTP::Request

use HTTP::Request;

my $browser = LWP::UserAgent->new;
my $request = HTTP::Request;
my $request->authentication_basic($user, $pass);
my $request->method("POST");
my $request->url($url);

# Create Content Byte String
my $uri = URI->new('http://');  #URL isn't needed, just the object
$uri->form_query(Name => $name, Address => $address);
my $content = $uri->query;

$request->content($content);

# Set the headers for the content
$request->header( "Content-Type" => "application/x-www-form-urlencoded" );
$request->header( "Content-Length" => length($content) );

# Now send your request through your browser
my $response = $browser->request($request);

您可以看到代码涉及更多。我想切换回,HTTP::Request::Common因为代码看起来更容易维护,但是如何处理身份验证?

4

1 回答 1

5

POST只是一个HTTP::Request对象的精美构造函数。使用它来构造您的请求对象,然后设置身份验证:

use HTTP::Request::Common;

my $browser = LWP::UserAgent->new;
my $request = POST $url, 
    Content => [
        Name => $name,
        Address => $address,
    ];

$request->authorization_basic($user, $pass); 

my $response = $browser->request($request);
于 2013-05-20T19:35:06.420 回答