【问题标题】:Perl: Need an LWP & HTTP::Request POST code that actually worksPerl:需要一个实际有效的 LWP 和 HTTP::Request POST 代码
【发布时间】:2018-06-20 03:34:27
【问题描述】:

我一直在挠头,试图让 LWP 和 HTTP::Request 实际将 POST 参数传递给 Web 服务器。 Web 服务器可以看到该请求是一个 POST 事务,但它没有获取传递的参数。我整天都在搜索这个并尝试了不同的东西,但我还没有找到有效的东西。 (网络服务器正在工作,我可以手动发送事务处理,并且在运行整个脚本时,我得到“200”状态,但我没有看到任何已发布的元素。任何帮助将不胜感激。Tnx。

my $ua2 = LWP::UserAgent->new;
$ua2->agent("Mozilla/5.0 (compatible; MSIE 6.0; Windows 98)");
my $req2 = HTTP::Request->new(POST => "$url", [ frm-advSearch => 'frmadvSearch' ]);
$req2->content_type('text/html');
my $res2 = $ua2->request($req2);
$http_stat = substr($res2->status_line,0,3);

【问题讨论】:

  • substr($res2->status_line,0,3) 最好写成$res2->code

标签: perl post httprequest lwp


【解决方案1】:
my $res = $ua->post($url,
   Content => [
      'frm-advSearch' => 'frmadvSearch',
   ],
);

简称

use HTTP::Request::Common qw( POST );

my $req = POST($url,
   Content => [
      'frm-advSearch' => 'frmadvSearch',
   ],
);

my $res = $ua->request($req);

【讨论】:

    【解决方案2】:

    这是一个Mojo::UserAgent 示例,我发现它更易于调试:

    use Mojo::UserAgent;
    my $ua = Mojo::UserAgent->new;
    $ua->transactor->name( 'Mozilla/5.0 (compatible; MSIE 6.0; Windows 98)' );
    
    my $url = 'http://www.example.com/form/';
    my $tx = $ua->post( $url, form => { 'frm-advSearch' => 'frmadvSearch' } );
    say $tx->req->to_string;
    

    $tx 中的事务知道该请求,因此我可以查看:

    POST /form/ HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    User-Agent: Mozilla/5.0 (compatible; MSIE 6.0; Windows 98)
    Accept-Encoding: gzip
    Host: www.example.com
    Content-Length: 26
    
    frm-advSearch=frmadvSearch
    

    【讨论】:

    • Re "我觉得更容易调试",say $tx->req->to_string; 并不比say $req2->to_string;say $tx->request->to_string; 更容易
    • 我发现它更容易。你可能不会。
    • 哦,我同意。少输入 4 个字符更容易。
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2016-04-11
    • 2012-09-22
    • 2023-03-16
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多