spaz has asked for the wisdom of the Perl Monks concerning the following question:

In a project of mine I need to send a POST statement to a webserver. I looked at LWP and LWP::UserAgent and didn't quite see what I needed -- I think. What I ended up doing was making my own Socket connection, and then printing a POST statement to it (code below) and reading in the results.

So fellow monks, based on the code below, did I need to roll my own? I'm sure somebody else can write this networking stuff better than I can.
#!/usr/bin/perl -w use IO::Socket; use strict; my $socket = &new_socket( { host => "foo.com", port => 80 } ); print $socket &new_post( { data => "foobar", path => "/cgi-bin/foobar.pl", host => "http://www.foo.com", referer => "http://www.foo.com/baz.html" } ); print OUT while( <$socket> ); ######################################### sub new_socket { my( $args ) = @_; return IO::Socket::INET->new( PeerAddr => $$args{host}, PeerPort => $$args{port}, Proto => "tcp", Type => SOCK_STREAM ); } sub new_post { my( $args ) = @_; my $length = length( $$args{data} ); my $post = "POST $$args{path} HTTP/1.0\n"; $post .= "Host: $$args{host}\n"; $post .= "Accept: text/html, text/plain, text/richtext"; $post .= ", text/enriched\n"; $post .= "Accept-Encoding: gzip, compress\n"; $post .= "Accept-Language: en\n"; $post .= "Pragma: no-cache\n"; $post .= "Cache-Control: no-cache\n"; $post .= "User-Agent: Lynx/2.8.3dev.18 libwww-FM/2.14\n"; $post .= "Referer: $$args{referer}\n"; $post .= "Content-type: application/x-www-form-urlencoded\n"; $post .= "Content-length: $length\n\n"; $post .= "$$args{data}\n"; return $post; }

Replies are listed 'Best First'.
Re: Did I have to roll my own?
by c-era (Curate) on Jan 19, 2001 at 01:02 UTC
    You can use LWP::UserAgent
    use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $req = HTTP::Request->new(POST => 'http://www.foobar.com/cgi-bin/fo +obar'); $req->content_type('application/x-www-form-urlencoded'); $req->content('foobar=5'); my $res = $ua->request($req); print $res->as_string;
    You can get more information by looking in lwpcook.(pod|html) that came with libwww-perl.
      Even simpler would be to follow the advice in lwpcook:
      Lazy people use the HTTP::Request::Common module to set up a suitable POST request message (it handles all the escap- ing issues) and has a suitable default for the con- tent_type: use HTTP::Request::Common qw(POST); use LWP::UserAgent; $ua = LWP::UserAgent->new; my $req = POST 'http://www.perl.com/cgi-bin/BugGlimpse', [ search => 'www', errors => 0 ]; print $ua->request($req)->as_string; The lwp-request program (alias POST) that is distributed with the library can also be used for posting data.

      -- Randal L. Schwartz, Perl hacker