To work with HTTP in Perl, we will use LWP -- the Library for WWW in Perl.
Issuing GET Requests
GET requests are pretty trivial with LWP, especially if you don't care much about setting headers in the request or reading headers in the response:
use LWP::Simple; my $url = 'http://www.acme.com/products/3322'; # ACME boomerang my $response = get $url; die 'Error getting $url' unless defined $response;
For more advanced features, you'll need to create a browser object, thus:
use LWP; my $browser = LWP::UserAgent->new; my $url = 'http://www.acme.com/products/3322'; # Issue request, with an HTTP header my $response = $browser->get($url, 'User-Agent' => 'Mozilla/4.0 (compatible; MSIE 7.0)', ); die 'Error getting $url' unless $response->is_success; print 'Content type is ', $response->content_type; print 'Content is:'; print $response->content;
Issuing POST Requests
The same browser object defined above can be used to issue POST requests, too. Field names are directly mapped to values, thus:
my $response = $browser->post($url, [ 'firstName' = 'John', 'lastName' = 'Doe' ], ); die 'Error getting $url' unless $response->is_success;
Note that the UserAgent class allows you to easily set and read cookies, too, but these should be avoided in REST designs.