0

如何使用 perl mechanize 模块提交有效的 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);

还是我应该做/添加其他东西?

4

1 回答 1

2

通常人们会使用该JSON模块,以便您可以在 Perl 中创建数据结构,然后序列化为 JSON 格式的字符串

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

请注意,\0and\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 );
于 2013-04-13T13:08:48.400 回答