我尝试使用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
,因为代码看起来更容易维护,但我该如何处理身份验证呢?
答案 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);