Perl:使用HTTP :: Request :: Common发布身份验证

时间:2013-05-20 19:12:44

标签: perl httprequest lwp

我尝试使用HTTP::Request::Common为网址发帖。不幸的是,它似乎不适用于身份验证,我不得不切换回普通的'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,因为代码看起来更容易维护,但我该如何处理身份验证呢?

1 个答案:

答案 0 :(得分: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);