How to send HTTP GET or POST request in Perl

Last updated on September 29, 2020 by Dan Nanni

In Perl, there are many ways to make HTTP requests by using existing Perl modules. In this tutorial, I will show examples of sending HTTP requests in Perl by using LWP Perl module. The code snippets presented here illustrate how to set HTTP request header fields, as well as data enclosed in a request body.

Install LWP Perl Module in Linux

In order to use LWP Perl module, you need to install it first.

For Ubuntu or Debian:

$ sudo apt-get install libwww-perl

For CentOS, Fedora or RHEL:

$ sudo yum install perl-libwww-perl.noarch

For any Linux distribution using CPAN:

An alternative way to install LWP module is by using CPAN. Assuming that you have basic development environnment set up (e.g., build-essential on Debian-based system), you can run:
$ sudo perl -MCPAN -e 'install Bundle::LWP'

HTTP GET Perl example

Once you installed LWP module on your system, you can use the following Perl script to issue HTTP GET requests.

use LWP::UserAgent;

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

my $server_endpoint = "http://192.168.1.1:8000/service";

# set custom HTTP request header fields
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('content-type' => 'application/json');
$req->header('x-auth-token' => 'kfksj48sdfj4jd9d');

my $resp = $ua->request($req);
if ($resp->is_success) {
    my $message = $resp->decoded_content;
    print "Received reply: $messagen";
}
else {
    print "HTTP GET error code: ", $resp->code, "n";
    print "HTTP GET error message: ", $resp->message, "n";
}

HTTP POST Perl example

The following Perl script issues HTTP POST requests.

use LWP::UserAgent;

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

my $server_endpoint = "http://192.168.1.1:8000/service";

# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');
$req->header('x-auth-token' => 'kfksj48sdfj4jd9d');

# add POST data to HTTP request body
my $post_data = '{ "name": "Dan", "address": "NY" }';
$req->content($post_data);

my $resp = $ua->request($req);
if ($resp->is_success) {
    my $message = $resp->decoded_content;
    print "Received reply: $messagen";
}
else {
    print "HTTP POST error code: ", $resp->code, "n";
    print "HTTP POST error message: ", $resp->message, "n";
}

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean