简体   繁体   English

如何使用Perl和LWP发布非键/值对数据

[英]How to POST non key/value pair data with Perl and LWP

This "question" is asking for clarification on the answer here: How can I make a JSON POST request with LWP? 这个“问题”要求在这里对答案进行说明: 如何使用LWP发出JSON POST请求?

I don't have the reputation to comment on the answer, and felt that it was inappropriate to post my question as an answer. 我没有对评论发表评论的声誉,并且认为发布我的问题作为答案是不合适的。

Specifically, I'm trying to post JSON data (just like the other question-asker) instead of key-value pairs. 具体来说,我正在尝试发布JSON数据(就像其他提问者一样),而不是键值对。

Why does this work: 为什么这样做:

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

But this does not: 但这不是:

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

...and neither does this: ...而且这也不是:

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

I have read the manual for both HTTP::Request::Common and LWP::Useragent, and I think I'm just looking at the wrong thing. 我已经阅读了HTTP :: Request :: Common和LWP :: Useragent的手册,我认为我只是在看错东西。

Again, the first example works well, but I'd really like to understand this better. 同样,第一个示例运行良好,但我真的很想更好地理解这一点。

Thanks. 谢谢。

Why should it work? 为什么要运作? From the 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

You want 你要

POST($uri, Content => $json)

Unless this is part of a much larger application (and possibly still then), I might suggest using Mojo::UserAgent which has very easy tools for doing such things. 除非这是更大的应用程序的一部分(否则可能还会),否则我建议使用Mojo :: UserAgent ,它具有执行此类操作的非常简单的工具。

use strict;
use warnings;

use Mojo::UserAgent;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM