1 use LWP::UserAgent; 2 use HTTP::Cookies; 3 4 my $ua = LWP::UserAgent->new; 5 $ua->cookie_jar(HTTP::Cookies->new( 6 file => "cookies.txt", 7 autosave => 1)); 8 9 my $req = HTTP::Request->new(GET => "http://www.example.com/"); 10 11 my $res = $ua->request($req); 12 print $res->status_line; 13 #用HTTP::Cookies来创建cookie保存的地方
#或者可以如下所示
1 use LWP::UserAgent; 2 use HTTP::Cookies; 3 $cookie_jar = HTTP::Cookies->new( 4 file => "/home/perl/cookies.dat", 5 autosave => 1, 6 ); 7 $ua->cookir_jar($cookie_jar); 8 #还可以这样 9 $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" }); 10 #注意这里是cookie_jar参数要求是个字典
还有, 如果你是想在发送请求时一起发送指定cookie, 可以这样:
1 use LWP::UserAgent; 2 my $ua = LWP::UserAgent->new; 3 4 my $req = HTTP::Request->new(GET => 'http://www.example.com/'); 5 $req->header('Cookie' => "key1=value1;key2=value2"); 6 #这个header可参考HTTP::Headers模块 7 my $res = $ua->request($req); 8 print $res->status_line