2

尝试从脚本发送POST请求时出现错误:perl

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->credentials($netloc,$realm,$username,$password);
use HTTP::Request::Common;
my $req = HTTP::Request::Common::POST($url,'content' => $conf);

$req->as_string()

POST http:.....
Content-Length: 31003
Content-Type: application/x-www-form-urlencoded

.....&createTime=1361370652541&parameters=HASH(0x28fd658)&parameters=HASH(0x28fd670)&parameters=HASH(0x28fd6e8)&parameters=HASH(0x28fd760)&nodes=32&.....&alerts=HASH(0x632d00)&alerts=HASH(0x245abd0)&.....

我得到的错误是

Unexpected character ('H' (code 72)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')

这让我怀疑问题出在重复的 parameters=HASH(...)alerts=HASH(...)元素上;相反,我想看到类似的东西

alerts=%5B%7B%22email%22%3A%22foo%40bar.com%22%2C%22type%22%3A%221%22%2C%22timeout%22%3A%22%22%7D%5D    

$conf是哈希引用,$conf->{"parameters"} and $conf->{"alerts"}` 是数组引用(其元素是哈希引用)。

我究竟做错了什么?

4

1 回答 1

3

You can't post references; you presumably need to serialize them in some way; what is the server expecting?

From the error it looks like either the entire array or possibly each of the hashes in it should be serialized in JSON:

use JSON;  # preferably have JSON::XS installed
my %prepared_conf = %$conf;
for my $field ( 'parameters', 'alerts' ) {
    $prepared_conf{$field} =
        JSON::to_json( $prepared_conf->{$field}, { 'ascii' => 1 } );
}
my $req = HTTP::Request::Common::POST($url,'content' => \%prepared_conf);
于 2013-02-26T16:30:30.777 回答