Reputation: 3233
I have written a Perl Script to send an HTTP GET request to a website. In the request headers, I want to set multiple cookies, so that the header looks like
Cookie: key1 = val1; key2 = val2; key3 = val3
I am using HTTP::Cookies
to set the cookies in a WWW::Mechanize
object.
However set_cookie()
can only add one cookie to the cookie jar. How can I add multiple cookies?
If I call the set_cookie()
method multiple times, only the last cookie set in the cookie_jar is sent in the HTTP GET request.
Below is the code I have written
#! /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();
Below is how the HTTP GET request looks like:
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"
As you can see, in the HTTP GET request headers above, only the last cookie key3
is sent. How can I send multiple cookies?
Upvotes: 1
Views: 1528
Reputation: 126742
This appears to work fine.
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";
output
GET http://www.example.com/
Cookie: key2=val2; key1=val1; key3=val3
Cookie2: $Version="1"
Upvotes: 2