Ronin Tom
Ronin Tom

Reputation: 188

How to setup the content of a HTTP::Request with form data in PERL

I would like to send form data via the http post method. Therefore I would like to setup a HTTP::Request with the appropriate data, but I do not know how to do this. I would like to do something like this

use strict;
use warnings;
use 5.010;

use LWP::UserAgent;
use HTTP::Headers;
use HTTP::Request;

my $browser = LWP::UserAgent->new();
my $header = HTTP::Headers->new();
my $data;

# What I have to do here to initialize $header and $data
# with name=Pete and age=35 for example 

my $request = HTTP::Request->new( POST, "http://www.example.com", $header, $data );

my $response = $browser->request( $request );

say $response->as_string();

exit;

I have not found any full example using HTTP::Request yet. Using LWP::Simple is out of question.

Upvotes: 3

Views: 4422

Answers (2)

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

You can supply form values to the post method of your LWP::UserAgent object. From the documentation:

$ua->post( $url, \%form )

$ua->post( $url, \@form )

$ua->post( $url, \%form, $field_name => $value, ... )

$ua->post( $url, $field_name => $value,... Content => \%form )

$ua->post( $url, $field_name => $value,... Content => \@form )

$ua->post( $url, $field_name => $value,... Content => $content )

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.

As with the get method, you can generate additional headers by passing them as name/value pairs. The following will POST the form data in %form and set the Cookie header:

my %form = (
    foo    => 'bar',
    answer => 42
);

my $ua = LWP::UserAgent->new;
$ua->post( 'http://www.example.com', Cookie => $cookie, \%form );

This actually uses HTTP::Request::Common's POST function behind the scenes to generate the request. The HTTP::Request::Common documentation has examples of how to generate more complex requests.

Upvotes: 3

Dave Cross
Dave Cross

Reputation: 69224

HTTP::Request is a subclass of HTTP::Message. I think that's where you will find the methods that you want.

Upvotes: 0

Related Questions