You are viewing a plain text version of this content. The canonical link for it is here.
Posted to modperl@perl.apache.org by Islandman <sc...@centurytel.net> on 2001/06/27 02:52:02 UTC

pass cookie along with the POST request?

The small code segment below will get the contents of a web page using a
perl script. The site I want to access wants a cookie sent as well. 

There is a cookie for this site is in my ~/.netscape/cookies file.  How
do I change the code below so I can fake pass the cookie along with the
POST request?

Will I need to modify the format of what is in ~/.netscape/cookies?

------------------------------
use strict;
use LWP::UserAgent;
use HTTP::Request::Common;
my $URL = 'http://www.yahoo.com';
my $ua = LWP::UserAgent->new;
my $response = $ua->request(POST "$URL");

if ($response->is_success) {
   print $response->content;
} else {
   print "Bad luck this time\n";
}

Thanks!
 -Brian

Re: pass cookie along with the POST request?

Posted by darren chamberlain <dl...@users.sourceforge.net>.
Islandman <sc...@centurytel.net> said something to this effect on 06/26/2001:
> The small code segment below will get the contents of a web page using a
> perl script. The site I want to access wants a cookie sent as well. 
> 
> There is a cookie for this site is in my ~/.netscape/cookies file.  How
> do I change the code below so I can fake pass the cookie along with the
> POST request?
> 
> Will I need to modify the format of what is in ~/.netscape/cookies?

Create a HTTP::Cookies::Netscape object:

use HTTP::Cookies;
my $c = HTTP::Cookies::Netscape->new(
                          File     => "$ENV{HOME}/.netscape/cookies",
                          AutoSave => 1,
                      );

HTTP::Cookies::Netscape objects have a hashref called COOKIES,
which is a hash of hashes of hashes of lists. Access the cookies'
values as such:

my $val = $c->{COOKIES}->{$host}->{$path}->{$cookie_name}->[1];

perldoc LWP::UserAgent tells us:

       $ua->cookie_jar([$cookies])
           Get/set the HTTP::Cookies object to use.  The default
           is to have no cookie_jar, i.e. never automatically add
           "Cookie" headers to the requests.

So you don't have to access the values directly. Add this to your
code:

> ------------------------------
> use strict;
> use LWP::UserAgent;
> use HTTP::Request::Common;
use HTTP::Cookies;
> my $URL = 'http://www.yahoo.com';
> my $ua = LWP::UserAgent->new;
> my $response = $ua->request(POST "$URL");
my $jar =  HTTP::Cookies::Netscape->new(
              File     => "$ENV{HOME}/.netscape/cookies",
              AutoSave => 1,
           );
$ua->cookie_jar($jar);
> 
> if ($response->is_success) {
>    print $response->content;
> } else {
>    print "Bad luck this time\n";
> }

Untested, but the docs say it should work.

(darren)

-- 
"Quiet and courteous" is often mistaken for "kind and polite."
    -- Andrew Langmead