http beginner
How to handle HTTP response codes with LWP::UserAgent in Perl?
Question
How to handle HTTP response codes with LWP::UserAgent in Perl?
Handling HTTP response codes with LWP::UserAgent in Perl is straightforward and essential when building web clients. The LWP::UserAgent module provides a rich interface for making HTTP requests and inspecting the returned responses, including status codes, headers, and content.
Basic Concepts
LWP::UserAgentcreates a web client that can send HTTP requests.- The
requestor shortcut methods likegetreturn an HTTP::Response object. - HTTP status codes (e.g., 200, 404, 500) indicate whether the request succeeded or failed.
- Use
$response->codeto get the numeric status code, and$response->messagefor the textual phrase. $response->is_successis a boolean method returning true for 2xx responses.
Common Pattern to Handle Response Codes
Check $response->is_success to confirm the request succeeded, else handle errors based on the returned status code.
Example: Making a GET request and handling response codes
use strict;
use warnings;
use LWP::UserAgent;
my $url = 'http://httpbin.org/status/404'; # Change URL to test different codes
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $response = $ua->get($url);
if ($response->is_success) {
print "Request succeeded with code ", $response->code, "\n";
print "Content:\n", $response->decoded_content, "\n";
}
else {
print "Request failed with code ", $response->code, " (", $response->message, ")\n";
# Handle specific response codes
if ($response->code == 404) {
print "Error: Not Found - The requested URL was not found on the server.\n";
}
elsif ($response->code == 500) {
print "Error: Internal Server Error - The server encountered an unexpected condition.\n";
}
else {
print "Unhandled HTTP status code.\n";
}
}
Explanation
$ua->get($url)sends a GET request to the given URL.- The returned
$responseis anHTTP::Responseobject. $response->is_successchecks if the status code is 2xx.- Access
$response->codeand$response->messageto examine the HTTP status. - The example shows how to specialize handling for common codes like 404 and 500.
$response->decoded_contentreturns content decoded according to headers.
Version Notes and Pitfalls
LWP::UserAgenthas been stable since Perl 5.8, and the provided interface applies to Perl 5.10 and later.- Always check
is_successbefore assuming the content is valid to avoid misleading data. - Timeouts and networking errors also cause failures; check
$response->status_lineto debug network issues. - Use
decoded_contentto handle character encoding correctly instead ofcontent. - Beware of redirects;
LWP::UserAgentfollows them by default. To customize, check$response->previous.
By following this approach, you can robustly handle HTTP responses in your Perl scripts using LWP::UserAgent, gracefully reacting to errors or success conditions.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 1724ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Request failed with code 404 (NOT FOUND)
Error: Not Found - The requested URL was not found on the server.
STDERR
(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?