Form submission with LWP, https, and authentication

From Bjoern Hassler

Jump to: navigation, search


[edit] 1 Form submission with LWP, https, and authentication

This page gives an example of a minimal perl script to submit a form using perl/LWP, https, and authentication. As an example we use a submission to the simple timesheet (http://simmantools.sourceforge.net/).

Make sure you have Crypt::SSLeay. If not, you can use

sudo perl -MCPAN -e "install Crypt::SSLeay"

to install it. (If you don't have Crypt::SSLeay the script will still run, but you'll get a connection error.)

Here's the script:

#!/path/to/perl
use strict;
use LWP::UserAgent;
use HTTP::Request::Common;

my $myurl = "https://some.server/some/dir/timesheet.pl";

my %formfields = (
    "date" => "19-1-2009",
    "Project0" => "Test",
    "Mon0" => "1",
    "name"=>"Some Name",
    "submit" => "Save"
);

my $ua = new LWP::UserAgent;

$ua->protocols_allowed( [ 'http','https'] );
$ua->credentials(
 'some.server:443',
 'realm',
 'username' , 'password'
);

my $page = $ua->request(POST $myurl,\%formfields);

if ($page->is_success) {
   print $page->content;
} else {
   print $page->message;
}

Some explanations: There are quite a few LWP examples about, but I couldn't find one which has both https and authentication.

You do need the right port:

 'some.server:443',

Some examples used port 80, but it depends on what the server uses. You also need the correct 'realm' in the credentials:

 'realm',

which will typically be a phrase such as 'please log in', or 'restricted access only'. Make sure you put the protocol (https) into the right places: It should go into the url, but not into the credentials.

[edit] 2 Links