waldo22
waldo22

Reputation: 33

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?

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.

Upvotes: 1

Views: 785

Answers (2)

Joel Berger
Joel Berger

Reputation: 20280

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

Upvotes: 1

ikegami
ikegami

Reputation: 385575

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)

Upvotes: 5

Related Questions