How to make an HTTP GET request using LWP::UserAgent in Perl?
Question
How to make an HTTP GET request using LWP::UserAgent in Perl?
To make an HTTP GET request in Perl, LWP::UserAgent is one of the most popular core modules providing a clean, flexible interface for web interactions. It allows you to fetch URLs, handle headers, and get response content with ease.
Here is a step-by-step explanation with a runnable example to demonstrate how to perform a simple HTTP GET request using LWP::UserAgent:
Key Concepts:
LWP::UserAgentis a high-level HTTP client.- It creates a user-agent object to make requests
- HTTP responses are returned as
HTTP::Responseobjects. - You can check response success/failure with
is_success, and get content withdecoded_content. - Perl sigils indicate variable types:
$for scalars (like objects),@for arrays, and%for hashes.
Simple Working Example
use strict;
use warnings;
use LWP::UserAgent;
# Create a user agent object
my $ua = LWP::UserAgent->new;
# URL to fetch
my $url = 'http://www.example.com';
# Make the GET request
my $response = $ua->get($url);
# Check if the request was successful
if ($response->is_success) {
print "Success! Response content:\n";
# decoded_content handles character encoding correctly
print $response->decoded_content;
} else {
print "HTTP GET failed: ", $response->status_line, "\n";
}
Explanation
The example above performs these steps:
- Creates a
LWP::UserAgentobject called$ua. - Defines a URL to fetch (
http://www.example.com). - Calls the
getmethod on the user-agent object. - The
getmethod returns anHTTP::Responseobject stored in$response. - It uses
is_successto test for HTTP status 2xx. - If successful, it prints the body of the response using
decoded_contentwhich respects content encoding (UTF-8, gzip, etc). - If failed, it prints an error message with the HTTP code.
Common Pitfalls and Tips
- Always check
is_successto avoid blindly trusting the response content. decoded_contentis preferred overcontentto handle character encoding transparently.- Timeouts and redirects can be configured via
LWP::UserAgentattributes. - Be careful with HTTPS URLs;
LWP::UserAgentsupports them but requires underlying SSL modules installed. - Perl’s context:
getreturns a scalarHTTP::Responseobject. - You can add headers by passing a second argument to
get, e.g.$ua->get($url, 'Accept' => 'application/json').
Version Note
LWP::UserAgent is stable and available in Perl 5 distributions by default from very early versions. The usage remains consistent for Perl 5.6 and later. For HTTPS support, ensure that IO::Socket::SSL and related modules are installed.
This approach is a great starting point for basic HTTP requests in Perl. From here, you can explore POST requests, adding headers, cookies, and other features.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 1703ms
Success! Response content:
<!doctype html><html lang="en"><head><title>Example Domain</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{background:#eee;width:60vw;margin:15vh auto;font-family:system-ui,sans-serif}h1{font-size:1.5em}div{opacity:0.8}a:link,a:visited{color:#348}</style><body><div><h1>Example Domain</h1><p>This domain is for use in documentation examples without needing permission. Avoid use in operations.<p><a href="https://iana.org/domains/example">Learn more</a></div></body></html>
(empty)Was this helpful?
Related Questions
- How to handle gzip compressed responses with LWP in Perl?
- How to use LWP::Simple for quick GET requests in Perl?
- How to parse HTML response with HTML::TreeBuilder in Perl?
- How to use Mojo::UserAgent for HTTP requests in Perl?
- How to set connection keep-alive with LWP::UserAgent in Perl?
- How to use LWP::Protocol::https for HTTPS requests in Perl?