【问题标题】:How to POST non key/value pair data with Perl and LWP如何使用 Perl 和 LWP POST 非键/值对数据
【发布时间】:2013-05-23 21:18:23
【问题描述】:

这个“问题”要求澄清这里的答案: How can I make a JSON POST request with LWP?

我没有评论答案的声誉,并且认为将我的问题作为答案发布是不合适的。

具体来说,我正在尝试发布 JSON 数据(就像其他提问者一样)而不是键值对。

为什么会这样:

my $lwp = LWP::UserAgent->new;

my $req = HTTP::Request->new( 'POST', $uri );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );

my $response = $lwp->request( $req );

但这不是:

my $req= POST( $uri, $json);  ### this works for key/value pairs
$req->header( 'Content-Type' => 'application/json' );
my $response = $lwp->request( $req);

...这也不是:

my $response = $lwp->request(POST $uri, ['Content-Type' => 'application/json'], $json);

我已经阅读了 HTTP::Request::Common 和 LWP::Useragent 的手册,但我认为我只是看错了。

同样,第一个示例运行良好,但我真的很想更好地理解这一点。

谢谢。

【问题讨论】:

    标签: json perl http-post lwp


    【解决方案1】:

    为什么它应该起作用?来自docs

    POST $url
    POST $url, Header => Value,...
    POST $url, $form_ref, Header => Value,...
    POST $url, Header => Value,..., Content => $form_ref
    POST $url, Header => Value,..., Content => $content
    

    你想要

    POST($uri, Content => $json)
    

    【讨论】:

      【解决方案2】:

      除非这是一个更大的应用程序的一部分(并且可能仍然如此),否则我可能会建议使用Mojo::UserAgent,它有非常简单的工具来做这些事情。

      use strict;
      use warnings;
      
      use Mojo::UserAgent;
      
      my $ua = Mojo::UserAgent->new;
      $ua->post( $uri, json => $json );
      

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多