How can I make a JSON POST request with LWP?

后端 未结 4 1792
说谎
说谎 2020-12-12 21:03

If you try to login at https://orbit.theplanet.com/Login.aspx?url=/Default.aspx (use any username/password combination), you can see that the login credentials are sent as a

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 21:36

    The page is just using an "anonymized" (without name) input, which happens to be in JSON format.

    You should be able to use $ua->post($url, ..., Content => $content), which in turn use the POST() function from 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());
    }
    

    Alternatively, you can also use an hash for the JSON input:

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

提交回复
热议问题