原文:http://hi.baidu.com/jx89/blog/item/7e21cc035b90da8be950cde8.html
网上见过很多这样的例子,就是教程很少。
#!/usr/bin/perl
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent(" Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB6.4; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
my $request = HTTP::Request->new(GET=>'http://hi.baidu.com/jx89/');
$request->header(Accept => "*/*");
$request->header(Accept-Language => ": zh-cn");
$request->header(Accept-Encoding => "gzip, deflate");
$response=$ua->request($request);
if ($response->is_success)
{
print $response->content;
}
else
{
print $response->status_line, "\n";
}
或者直接这样:
#!/usr/bin/perl
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$res=$ua->get('http://hi.baidu.com/jx89/');
if ($response->is_success)
{
print $response->content;
}
else
{
print $response->status_line, "\n";
}
这样更简单,不过可以设置的东西少了:
#!/usr/bin/perl
use LWP::Simple;
$content = get("http://hi.baidu.com/jx89/");
die "Couldn't get it!" unless defined $content;
print $content;
HTTP Request的用法有几种:
$r = HTTP::Request->new( $method, $uri ) $r = HTTP::Request->new( $method, $uri, $header ) $r = HTTP::Request->new( $method, $uri, $header, $content ) 其中$uri可以直接输网址,也可以先定义$uri='http://hi.baidu.com' header属性可以设置也是比较有用的。 UserAgent有timeout、agent、from、parse_head、proxy、credentials等属性, 这些设置是可选的,比如:$ua->agent("my ");
$ua->timeout(90); 这里是说http请求,其实也不限于http,ftp等都可以的。