perl傳送http請求

zk1878發表於2011-04-09

原文: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等都可以的。

相關文章