Friday, July 10, 2009

Perl: Http::Cookies not saving cookie correctly

The below code for saving the http cookie after requesting some data over http is not working!!! Did you face this kind of problem anyway?

$cookie_jar->save()


For example the server sent you 4 cookies. But your cookie_jar is only saving the 2 of them, and rest of the two are ignored. Do you know the reason behind this?

It's not a bug of http cookies of perl, or lwp. Just lack of knowing the issue. Initially I thought it was a bug. The rest of the two cookies are session cookie. And it will die when you'll close your browser( this case your LWP ). That's why Http::Cookies is not saving the cookie on your file. Here is what it was said on the docs of HTTP::Cookies,

$cookie_jar->save
$cookie_jar->save( $file )

This method file saves the state of the $cookie_jar to a file. The state can then be restored later using the load() method. If a filename is not specified we will use the name specified during construction. If the attribute ignore_discard is set, then we will even save cookies that are marked to be discarded.

The default is to save a sequence of "Set-Cookie3" lines. "Set-Cookie3" is a proprietary LWP format, not known to be compatible with any browser. The HTTP::Cookies::Netscape sub-class can be used to save in a format compatible with Netscape.
HTTP::Cookies

So, this means you have to notify the cookie_jar to save your session cookie too. To do this you have to do as below.

$cookie_jar = HTTP::Cookies->new(
file => "cookie.txt",
ignore_discard => 1,
);

$cookie_jar = HTTP::Cookies->new(
ignore_discard => 1,
);

2 comments:

mikecanz said...

This was exactly what I needed. Thanks for the post.

Anonymous said...

thx! it's helped me.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...