需要在perl中发送JSON请求

roo*_*oot 1 perl json perl-module

我无法完成这项工作,我一直收到400错误的请求响应.非常感谢任何帮助,因为这是我第一次尝试编写perl和使用JSON.我不得不删除一些敏感数据,因为这是工作的东西.这个脚本的目的是简单地点击通过JSON发送POST数据的URL并打印响应.

#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;
use JSON;


my $ua = LWP::UserAgent->new;
my $req = POST 'URL IS HERE';
my $res = $ua->request($req);
my $json = '{"warehouseId": "ID",
"tagMap":
  {"cameraId":["Name of camera"]
  },
"searchStartTimeStamp": 0,
"searchEndTimeStamp": 100000000000000,
"pageSize": 1,
 "client": 
  {"id": "username",
   "type": "person"}
}';


$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );


    if ($res->is_success) {
print $req->content( $json );

    print $res->content;
} else {
    print $res->status_line . "\n";
}
exit 0;
Run Code Online (Sandbox Code Playgroud)

amo*_*mon 9

您在完全填充之前执行请求!该行执行请求:

my $res = $ua->request($req);
Run Code Online (Sandbox Code Playgroud)

但是几行之后,你填写了一些字段:

$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );
Run Code Online (Sandbox Code Playgroud)

尝试交换周围:

my $json = ...;

my $ua = LWP::UserAgent->new;
my $req = POST 'URL IS HERE';    
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );

my $res = $ua->request($req);
Run Code Online (Sandbox Code Playgroud)

哦,永远不会$res->content.该方法的价值通常不是可用的.你总是想要

$res->decoded_content;
Run Code Online (Sandbox Code Playgroud)