如果$ URL不存在或没有响应,如何将$ PageData设置为错误消息,例如“$ PageData = Page not found”?我似乎无法让它发挥作用。
use LWP::UserAgent;
use HTTP::Request;
my $URL = "http://www.MyDomain.com/;
my $Request = HTTP::Request->new("GET", $URL);
my $UserAgent = LWP::UserAgent->new(timeout => 5);
my $Result = $UserAgent->request($Request);
return unless $Result->is_success;
$PageData = $Result->content;
print $PageData;
答案 0 :(得分:0)
尝试使用库HTTP::Status并使用以下代码:
use ...
use HTTP::Status qw(:constants :is status_message);
my $url = ...
my $request = HTTP::Request->new(GET => $url);
my $ua = LWP::UserAgent->new;
my $response = $ua->request($request);
if ($response->is_error) {
print STDERR $response->status_line, "\n";
print STDERR status_message($response->status_line), "\n";
print STDERR $response->error_as_HTML, "\n";
}
else {
print $response->decoded_content;
}