【问题标题】:How to POST content with an HTTP Request (Perl)如何使用 HTTP 请求 (Perl) 发布内容
【发布时间】:2012-07-01 03:26:45
【问题描述】:
use LWP::UserAgent;
use Data::Dumper;

my $ua = new LWP::UserAgent;
$ua->agent("AgentName/0.1 " . $ua->agent);
my $req = new HTTP::Request POST => 'http://example.com';
$req->content('port=8', 'target=64'); #problem
my $res = $ua->request($req);

print Dumper($res->content);

如何使用 $req->content 发送多条内容? $req->content 期望什么样的数据?

它只发送最后一个。

编辑:

发现如果我将其格式化为“port=8&target=64”,它可以工作。有没有更好的办法?

【问题讨论】:

    标签: perl http lwp


    【解决方案1】:
    my $ua      = LWP::UserAgent->new(); 
    my $request = POST( $url, [ 'port' => 8, 'target' => 64 ] ); 
    my $content = $ua->request($request)->as_string(); 
    

    【讨论】:

    • 尽管问题中有代码,但我还是会采用完整的 OOP 方法:my $ua = LWP::UserAgent->new(); my $response = $ua->post($url, $parameter); my $content = $response->as_string();
    【解决方案2】:

    给出的答案对我不起作用。我还是遇到了和 OP 一样的问题。

    LWP::UserAgent 的文档需要哈希或数组引用。

    这行得通:

    my $url = 'https://www.google.com/recaptcha/api/siteverify';
    my $ua      = LWP::UserAgent->new(); 
    
    my %form;
    $form{'secret'}='xxxxxxxxxxxxxxxxxxxxxxx';
    $form{'response'}=$captchaResponse;
    
    my $response = $ua->post( $url, \%form ); 
    my $content = $response->as_string();
    

    【讨论】:

      【解决方案3】:

      将 LWP::UserAgent 和 HTTP::Request 一起使用,因为即使不是更频繁的练习,它也很常见,我对标准 POST 和 GET / request 几乎没有在 SO 除了 json 之外的讨论绝大多数都在使用。

      发布

          my $ua  = LWP::UserAgent->new();
          my $req = new HTTP::Request( 
             'POST' => "http://url/path", 
             ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
             'par1=par1value&par2=par2value'
          );
          $ua->request($req);
      

      GET 类似

          my $ua  = LWP::UserAgent->new();
          my $req = new HTTP::Request( 
             'GET' => "http://url/path", 
             ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
             'par1=par1value&par2=par2value' # or I presume attaching the query string directly to the url
          );
          $ua->request($req);
      

      另一种格式形式,其中前两个参数(method和url)没有融合成一个,不像前面那样,而是分开

      my $request = HTTP::Request->new( 'POST', $url, [ parameter1 => 'parameter1Value' ] );
      request->header( 'Content-Type' => 'application/json' )
      

      有一个类似的问题,但只考虑 LWP 和 Json,但它可能只能通过使用 LWP 和 HTTP::Request 来完成这可能并不明显

      How can I make a JSON POST request with LWP?

      注意: 我也特别发布了这个,因为即使在文档中也没有提到 POST/GET 的具体/简洁用法 https://metacpan.org/pod/HTTP::Request

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-09
        • 2020-02-29
        相关资源
        最近更新 更多