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.
LWP Perl Module in LinuxIn order to use LWP Perl module, you need to install it first.
$ sudo apt-get install libwww-perl
$ sudo yum install perl-libwww-perl.noarch
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'
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";
}
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";
}
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 ‒ About ‒ Write for Us ‒ Feed ‒ Powered by DigitalOcean