【问题标题】:perl www mechanize and JSONperl www mechanize 和 JSON
【发布时间】:2013-04-13 13:04:41
【问题描述】:

如何使用 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); 这样做是对的

或者我应该做/添加其他东西吗?

【问题讨论】:

    标签: json perl www-mechanize


    【解决方案1】:

    通常会使用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 );
    

    【讨论】:

    • 非常感谢 Joel 提供的 json 提示,但在我的服务器上根本无法安装 Mojo Useragent,我暂时被 perl WWW::Mechanize 困住了。我尝试发布 $mech->put($url,content => encode_json $json); $mech->post($url,content => encode_json $json);结果相同。仍然无法正确发送
    • @Shanthi 尝试使用 LWP::UserAgent 并用它做一个帖子。你有它是因为它是 WWW::Mechanize 的子类。它比 W:M 更适合您的任务。
    • @simbabque,IIRC 反过来,WWW::Mechanize 是 LWP::UserAgent 的子类。
    • @simbabque 我尝试了这种方法并解决了 JSON 问题,但会话/cookie 没有被传递给 mech 对象。 $req = HTTP::Request->new('POST', $url); $req->header('Content-Type' => 'application/json'); $req->内容($json); $mech->request($req);但是现在原始 cookie jar 数据消失了,因为这变成了一个新请求
    • @JoelBerger 你是对的,我的意思是一个基类。很着急,谢谢指正。 Shanthi:你需要一个专用的饼干罐。查看 LWP 的文档。
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多