Curl to Perl HTTP Request



伙计们,我需要将这个curl请求转换为LWP::UserAgent HTTP请求

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

我试过的是:

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

但回应称

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

您可以尝试使用以下POST请求:

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

既然你没有问,这里有一个Mojo示例:

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

它基本上与LWP相同,只是Mojo返回一个事务对象,这样您也可以处理请求。甚至在Mojo存在之前,这就是我在LWP想要的东西。

最新更新