I am trying to send a POST request to a REST web-service using the Perl LWP library. I am able to successfully complete the POST request with no errors; however, when I try to get the response content, it returns an empty sequence []
. I have sent POST requests to the web-service using the Postman application in Chrome, and it returns the expected response. It seems that this happens only for POST and PUT requests: GET requests return the expected content.
Here is my Perl code:
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;
use JSON;
use Data::Dumper;
my $url = "http://localhost:53076/api/excel(07375ebd-e21f-4ce4-91d7-49dc2de7ceb1)";
my $ua = LWP::UserAgent->new( keep_alive => 1 );
my $json = JSON->new->utf8->allow_nonref;
my @inputs = ( ( "key" => "A", "Value" => "12" ), ( "key" => "B", "Value" => "12" ) );
my @outputs = ( ( "key" => "A", "Value" => "12" ), ( "key" => "B", "Value" => "12" ) );
my %body;
$body{"Inputs"} = \@inputs;
$body{"Outputs"} = \@outputs;
my $jsonString = $json->encode(\%body);
my $response = $ua->post($url, "Content-Type" => "application/json; charset=utf-8", "Content" => $jsonString);
if ($response->is_success)
{
print "\n========== REQUEST CONTENT ==========\n";
print $response->decoded_content(), "\n";
}
else
{
print "\n========== ERROR ==========\n";
print "Error: ", $response->status_line(), "\n";
print $response->headers()->as_string(), "\n";
}
Am I doing something wrong?
In an expression, ()
doesn't do anything except to affect precedence. For example, 4 * ( 5 + 6 )
is different than 4 * 5 + 6
. As such,
my @inputs = ( ( key => "A", Value => "12" ), ( key => "B", Value => "12" ) );
is just a weird way of writing
my @inputs = ( "key", "A", "Value", "12", "key", "B", "Value", "12" );
If you want to create a hash and return a reference to it, it's done using {}
.
my @inputs = ( { key => "A", Value => "12" }, { key => "B", Value => "12" } );
my @outputs = ( { key => "A", Value => "12" }, { key => "B", Value => "12" } );
That's basically short for
my %anon_i1 = ( key => "A", Value => "12" );
my %anon_i2 = ( key => "B", Value => "12" );
my @inputs = ( \%anon_i1, \%anon_i2 );
my %anon_o1 = ( key => "A", Value => "12" );
my %anon_o2 = ( key => "B", Value => "12" );
my @outputs = ( \%anon_o1, \%anon_o2 );