具有空序列响应的Perl LWP帖子

时间:2015-02-20 20:24:35

标签: perl lwp-useragent

我正在尝试使用Perl LWP库向REST Web服务发送POST请求。我能够成功完成POST请求,没有错误;但是,当我尝试获取响应内容时,它返回一个空序列[]。我已经使用Chrome中的Postman应用程序向网络服务发送了POST请求,并返回了预期的响应。似乎这只发生在POST和PUT请求中:GET请求返回预期的内容。

这是我的Perl代码:

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

}

我做错了吗?

1 个答案:

答案 0 :(得分:3)

在表达式中,()除了影响优先级之外什么也不做。例如,4 * ( 5 + 6 )4 * 5 + 6不同。因此,

my @inputs = ( ( key => "A", Value => "12" ), ( key => "B", Value => "12" ) );

只是一种奇怪的写作方式

my @inputs = ( "key", "A", "Value", "12", "key", "B", "Value", "12" );

如果您想创建哈希并返回对它的引用,请使用{}完成。

my @inputs  = ( { key => "A", Value => "12" }, { key => "B", Value => "12" } );
my @outputs = ( { key => "A", Value => "12" }, { key => "B", Value => "12" } );

这基本上是

的缩写
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 );