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::UserAgent creates a web client that can send HTTP requests.
  • The request or shortcut methods like get return an HTTP::Response object.
  • HTTP status codes (e.g., 200, 404, 500) indicate whether the request succeeded or failed.
  • Use $response->code to get the numeric status code, and $response->message for the textual phrase.
  • $response->is_success is 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 $response is an HTTP::Response object.
  • $response->is_success checks if the status code is 2xx.
  • Access $response->code and $response->message to examine the HTTP status.
  • The example shows how to specialize handling for common codes like 404 and 500.
  • $response->decoded_content returns content decoded according to headers.

Version Notes and Pitfalls

  • LWP::UserAgent has been stable since Perl 5.8, and the provided interface applies to Perl 5.10 and later.
  • Always check is_success before assuming the content is valid to avoid misleading data.
  • Timeouts and networking errors also cause failures; check $response->status_line to debug network issues.
  • Use decoded_content to handle character encoding correctly instead of content.
  • Beware of redirects; LWP::UserAgent follows 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