代码之家  ›  专栏  ›  技术社区  ›  Richard Simões

如何使用LWP发出JSON POST请求?

  •  28
  • Richard Simões  · 技术社区  · 14 年前

    如果您尝试登录 https://orbit.theplanet.com/Login.aspx?url=/Default.aspx (使用任何用户名/密码组合),可以看到登录凭据是作为一组非传统的POST数据发送的:只是一个lonesome JSON字符串,没有普通的key=value对。

    具体来说,不是:

    username=foo&password=bar
    

    或者类似于:

    json={"username":"foo","password":"bar"}
    

    简单来说就是:

    {"username":"foo","password":"bar"}
    

    是否可以使用 LWP 或者另一个模块?我准备这么做 IO::Socket 但如果可以的话,我更喜欢更高级的。

    4 回复  |  直到 14 年前
        1
  •  70
  •   friedo    14 年前

    您需要手动构造HTTP请求并将其传递给LWP。应该采取如下措施:

    my $uri = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
    my $json = '{"username":"foo","password":"bar"}';
    my $req = HTTP::Request->new( 'POST', $uri );
    $req->header( 'Content-Type' => 'application/json' );
    $req->content( $json );
    

    然后可以使用LWP执行请求:

    my $lwp = LWP::UserAgent->new;
    $lwp->request( $req );
    
        2
  •  15
  •   hobbs    14 年前

    只需创建一个POST请求,将其作为主体,并将其交给LWP。

    my $req = HTTP::Request->new(POST => $url);
    $req->content_type('application/json');
    $req->content($json);
    
    my $ua = LWP::UserAgent->new; # You might want some options here
    my $res = $ua->request($req);
    # $res is an HTTP::Response, see the usual LWP docs.
    
        3
  •  9
  •   Paolo Rovelli    9 年前

    这个页面只是使用了一个“匿名”(没有名字)输入,碰巧是JSON格式的。

    你应该可以使用 $ua->post($url, ..., Content => $content) ,然后使用POST()函数 HTTP::Request::Common .

    use LWP::UserAgent;
    
    my $url = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
    my $json = '{"username": "foo", "password": "bar"}';
    
    my $ua = new LWP::UserAgent();
    $response = $ua->post($url, Content => $json);
    
    if ( $response->is_success() ) {
        print("SUCCESSFUL LOGIN!\n");
    }
    else {
        print("ERROR: " . $response->status_line());
    }
    

    或者,也可以对JSON输入使用散列:

    use JSON::XS qw(encode_json);
    
    ...
    
    my %json;
    $json{username} = "foo";
    $json{password} = "bar";
    
    ...
    
    $response = $ua->post($url, Content => encode_json(\%json));
    
        4
  •  1
  •   TheDrev    10 年前

    如果您真的想使用WWW::Mechanize,可以在post之前设置标题“content type”

    $mech->add_header( 
    'content-type' => 'application/json'
    );
    
    $mech->post($uri, Content => $json);