アットウィキロゴ

Perl : WEBアクセス

HTTPアクセス GET

use LWP::UserAgent;
use LWP::Simple;

#クライアントの作成
my $ua = LWP::UserAgent->new();
$ua->agent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
my $url = "http://www.yahoo.co.jp";
my $req = HTTP::Request->new('GET', $url);
my $response = $ua->request($req);
print $response->content;


HTTPアクセス POST

 my $ua = LWP::UserAgent->new();
$ua->agent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
my $req = HTTP::Request->new('POST', "http://www.yahoo.co.jp");
$req->content_type('application/x-www-form-urlencoded');
$req->content('a=1&b=2&c=%81%81');
print $res->content;


COOKIE を利用する

use LWP::UserAgent;
use LWP::Simple;
use HTTP::Cookies;
my $cookie_file = "cookie.txt";
my $cookie_jar = HTTP::Cookies->new(file => $cookie_file, autosave => 1, ignore_discard => 1);

my $ua = LWP::UserAgent->new();
$ua->agent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
$ua->cookie_jar($cookie_jar);
my $req = HTTP::Request->new('GET', 'http://www.yahoo.co.jp');
$res = &process_request($ua, $req);
print $res->as_string;

sub process_request {
    my ($ua, $request) = @_;
    my $res = $ua->request($request);
    while ($res->is_redirect) {
        my $url = $res->header('Location');
        $res = $ua->request(HTTP::Request->new(GET => $url));
    }return $res;
}

 

最終更新:2008年09月09日 15:55