Curl to Perl HTTP Request

636 Views Asked by At

Guys I need this curl request be translated to LWP::UserAgent HTTP Request

echo 'test{test="test"} 3' | curl -v --data-binary @- http://localhost:9090/api/metrics

What I've tried is this :

my $ua = LWP::UserAgent->new;
my $res = $ua->post('http://localhost:9090/api/metrics', ['test{test="test"}' => 3]);
die Dumper $res

But the response says

'_rc' => '400',
'_msg' => 'Bad Request',
'_content' => 'text format parsing error in line 1: unexpected end of input stream
2

There are 2 best solutions below

0
Håkon Hægland On

You can try use the following POST request:

use feature qw(say);
use strict;
use warnings;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new();
my $res = $ua->post('http://localhost:9090/api/metrics', Content => 'test{test="test"} 3');
if ($res->is_success) {
    say $res->decoded_content;
}
else {
    die $res->status_line;
}
0
brian d foy On

And, since you didn't ask, here's a Mojo example:

use v5.10;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new();
my $tx = $ua->post(
    'http://httpbin.org/post',
    => 'test{test="test"} 3'
    );
if ($tx->result->is_success) {
    say $tx->result->body;
}
else {
    die $tx->result->code;
}

It's basically the same as LWP except that Mojo returns a transaction object so you can play with the request too. It's something I wanted in LWP even before Mojo existed.