Search code examples
perljsonhttp-postlwp

How can I make a JSON POST request with LWP?


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 non-traditional set of POST data: just a lonesome JSON string and no normal key=value pair.

Specifically, instead of:

username=foo&password=bar

or even something like:

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

There's simply:

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

Is it possible to perform such a request with LWP or an alternative module? I am prepared to do so with IO::Socket but would prefer something more high-level if available.


Solution

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