如何使用perl mechanize module
提交有效的JSON请求我试过
use WWW::Mechanize;
use JSON;
my $mech=WWW::Mechanize->new(
stack_depth => 10,
timeout => 120,
autocheck => 0,
);
$mech->agent_alias( 'Windows Mozilla' );
my $json = '{"jsonrpc":"2.0","id":1,"params":{"query": {"limit":2000,"start":0,"orderBy":[{"columnName":"osName","direction":"Asc"}]},"refresh":true}}';
$url ="http://path/to/url/";
$mech->post($url,$json);
并且结果没有按预期进行它总是解析json错误。
所以我只是发布$mech->post($url,$cjson);
或者我应该做/添加别的东西?
答案 0 :(得分:2)
通常会使用JSON
模块,以便您可以在Perl中创建数据结构,然后serialize to a JSON formatted string。
$json_text = encode_json $perl_scalar
看起来像这样:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON qw/encode_json/;
my $data = {
"jsonrpc" => "2.0",
"id" => 1,
"params" => {
"query" => {
"limit" => 2000,
"start" => 0,
"orderBy" => [{
"columnName" => "osName",
"direction" => "Asc",
}],
},
"refresh" => \0,
},
};
print encode_json $data;
请注意,\0
和\1
可分别用作false和true。
然后,我很久没有使用过WWW :: Mechanize了,我也不打算深入研究文档,所以这里有一个使用Mojo::UserAgent的例子(更像是LWP) :: UserAgent而不是mech),它有一个内置的JSON处理程序:
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $data = {
"jsonrpc" => "2.0",
"id" => 1,
"params" => {
"query" => {
"limit" => 2000,
"start" => 0,
"orderBy" => [{
"columnName" => "osName",
"direction" => "Asc",
}],
},
"refresh" => \0,
},
};
my $url = "http://path/to/url/";
$ua->post( $url, json => $data );