Pregunta

This "question" is asking for clarification on the answer here: How can I make a JSON POST request with LWP?

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.

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.

Again, the first example works well, but I'd really like to understand this better.

Thanks.

¿Fue útil?

Solución

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)

Otros consejos

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.

use strict;
use warnings;

use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
$ua->post( $uri, json => $json );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top