【问题标题】:Perl: Using HTTP::Request::Common to post with authenticationPerl:使用 HTTP::Request::Common 发布身份验证
【发布时间】:2013-05-20 19:12:43
【问题描述】:

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

【问题讨论】:

    标签: perl httprequest lwp


    【解决方案1】:

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

    【讨论】:

    • 谢谢。这要容易得多。 perldoc 显示您在创建HTTP::Request 对象的同时执行LWP::UserAgent->request。是的,一旦你指出它就绝对有意义。语法让我陷入了循环。它是一种非面向对象的调用语法,实际上是一个构造函数。谢谢。这使我的程序更易于阅读。
    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2013-01-16
    • 2012-10-21
    • 2018-01-11
    • 2018-04-29
    • 2011-12-05
    相关资源
    最近更新 更多