How can I make a JSON POST request with LWP?

旧时模样 提交于 2019-11-29 20:19:18

You'll need to construct the HTTP request manually and pass that to LWP. Something like the following should do it:

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

Then you can execute the request with LWP:

my $lwp = LWP::UserAgent->new;
$lwp->request( $req );

Just create a POST request with that as the body, and give it to 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.

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

If you really want to use WWW::Mechanize you can set the header 'content-type' before post

$mech->add_header( 
'content-type' => 'application/json'
);

$mech->post($uri, Content => $json);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!