[Melbourne-pm] LWP::UserAgent to post to web form

Shlomi Fish shlomif at iglu.org.il
Wed Nov 15 02:24:08 PST 2006

On Wednesday 15 November 2006 10:10, Peter Machell wrote:
> Newbie alert. Help appreciated.
> I'm trying to script data to send to a web form.
> Please point me in the right direction if LWP::UserAgent is not an
> appropriate way to do this.

Well, LWP::UserAgent is an appropriate to do that. In many cases, however, 
WWW::Mechanize would be preferable.

> The code below is hitting the server but not sending a POST request.
> $ua returns LWP::UserAgent=HASH(0x82d0ab0)

Well, a few notes on the code:

> Thanks in advance,
> Peter.
> #!/usr/bin/perl
> use strict;
> use HTTP::Request::Common;
> use LWP::UserAgent;
> my($ua) = LWP::UserAgent->new;

You should really write

	my $ua = LWP::UserAgent->new;

my ($ua) calls the function in list context and returns only the first 
element. my $ua calls it in scalar context. I don't think it makes much 
difference here, but it could yield to subtle bugs.

> my($url) = 'http://foo.com/';


> my($send) = $ua->request(POST $url,
>          Content_Type => 'form-data',
>          Content      =>
>                  [
>                  userid          =>      'test',
>                  firstname       =>      'Test',
>                  ]
> );

You should use the $ua->post ( $url, \%form) method instead. Reading from the 
LWP::UserAgent POD document:

       $ua->post( $url, \%form )
       $ua->post( $url, \@form )
       $ua->post( $url, \%form, $field_name => $value, ... )
           This method will dispatch a "POST" request on the given $url, with
           %form or @form providing the key/value pairs for the fill-in form
           content. Additional headers and content options are the same as for
           the get() method.

           This method will use the POST() function from "HTTP::Request::Com
           mon" to build the request.  See HTTP::Request::Common for a details
           on how to pass form content and other advanced features.

If something doesn't work you can trace the conversation using wireshark:


Hope it helps,

	Shlomi Fish
> _______________________________________________
> Melbourne-pm mailing list
> Melbourne-pm at pm.org
> http://mail.pm.org/mailman/listinfo/melbourne-pm


Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

Chuck Norris wrote a complete Perl 6 implementation in a day but then
destroyed all evidence with his bare hands, so no one will know his secrets.

More information about the Melbourne-pm mailing list