Search code examples
perlcookieslwp

How to explicitly set cookie using LWP


I want to set some cookies for use in a HTTP::Request later. This is my code (shortest form that already exhibits the problem):

#!/usr/bin/perl -w

use strict;
use LWP::UserAgent;
use HTTP::Cookies;
use Data::Dumper; # DEBUG

my $ua = LWP::UserAgent->new;
$ua->agent("test.pl/0.1");
$ua->cookie_jar({ });
$ua->cookie_jar->set_cookie(0, "mykey", "myvalue", "/", "localhost", 80, 0, 0, 365 * 86400, 0);
print "Cookie jar: ", $ua->cookie_jar->as_string, "\n";
#print Dumper($ua->cookie_jar);
print "Cookies for URL: ", Dumper($ua->cookie_jar->get_cookies("http://localhost/"));

Output:

Cookie jar: Set-Cookie3: mykey=myvalue; path="/"; domain=localhost; port=80; expires="2020-05-05 23:40:21Z"; version=0

Cookies for URL: $VAR1 = {};

The cookie seems to have been added correctly to the cookie jar. However, when asking for the cookies that apply to the domain that I'm going to send the request to, it returns nothing instead of the expected cookie. And indeed, in my full program, when I try to do so, the request is sent, but the cookies aren't.

What am I missing?

In the end, I want to send an HTTPS request, not HTTP, so please also inform me how to properly set the cookie for that.


Solution

  • If you replace "localhost" with "example.com", you'll get the result you're looking for. Domain names must contain at least one dot.