我编写了一个Perl脚本来向网站发送HTTP GET请求。在请求标头中,我想设置多个cookie,以使标题看起来像
Cookie: key1 = val1; key2 = val2; key3 = val3
我正在使用HTTP::Cookies
在WWW::Mechanize
对象中设置Cookie。
但是set_cookie()
只能向cookie jar添加一个cookie。如何添加多个Cookie?
如果我多次调用set_cookie()
方法,则只会在HTTP GET请求中发送cookie_jar中设置的最后一个cookie。
以下是我编写的代码
#! /usr/bin/perl
use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
$cookies = HTTP::Cookies->new();
$cookies->set_cookie(0, 'key1', 'val1', '/', 'domain', 80, 0, 0, 86400, 0);
$cookies->set_cookie(0, 'key2', 'val2', '/', 'domain', 80, 0, 0, 86400, 0);
$cookies->set_cookie(0, 'key3', 'val3', '/', 'domain', 80, 0, 0, 86400, 0);
$mech=WWW::Mechanize->new(cookie_jar => $cookies, timeout => 20);
$mech->agent_alias('Windows IE 6');
$url = "http://domain/path";
eval{$mech->get($url)};
if ($@) {
print "there was an error in sending the HTTP GET request";
}
print $mech->content();
以下是HTTP GET请求的样子:
GET /path HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Accept-Encoding: gzip
Host: domain
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Cookie: key3=val3
Cookie2: $Version="1"
如您所见,在上面的HTTP GET请求标头中,只发送了最后一个Cookie key3
。如何发送多个cookie?
答案 0 :(得分:2)
这似乎工作正常。
use strict;
use warnings;
use HTTP::Request;
use HTTP::Cookies;
my $jar = HTTP::Cookies->new({});
$jar->set_cookie(0, 'key1', 'val1', '/', 'example.com', 80, 0, 0, 86400, 0);
$jar->set_cookie(0, 'key2', 'val2', '/', 'example.com', 80, 0, 0, 86400, 0);
$jar->set_cookie(0, 'key3', 'val3', '/', 'example.com', 80, 0, 0, 86400, 0);
my $request = HTTP::Request->new( qw{ GET http://www.example.com/ } );
$jar->add_cookie_header($request);
print $request->as_string, "\n";
<强>输出强>
GET http://www.example.com/
Cookie: key2=val2; key1=val1; key3=val3
Cookie2: $Version="1"