2

如果 $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;
4

1 回答 1

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;
}
于 2012-06-16T15:27:50.937 回答