如何从perl中的cookie jar获取会话ID?

时间:2014-09-17 09:57:28

标签: perl

我的问题很简单..这是如何从cookie jar获取会话ID ...我尝试过以下代码: -

use warnings;
use HTTP::Cookies;
use HTTP::Request::Common;
use LWP::UserAgent;

$ua = new LWP::UserAgent;
if ( !$ua ) {
    print "Can not get the page :UserAgent fialed \n";
    return 0;
}

my $cookies = new HTTP::Cookies( file => './cookies.dat', autosave => 1 );
$ua->cookie_jar($cookies);

# push does all magic to exrtact cookies and add to header for further reqs. useragent should be newer
push @{ $ua->requests_redirectable }, 'POST';
$result = $ua->request(
    POST "URL",
    {   Username => 'admin',
        Password => 'admin',
        Submit   => 'Submit',
    }
);
my $session_id = $cookies->extract_cookies($result);
print $session_id->content;
print "\n\n";
$resp = $result->content;
#print "Result is \n\n\n $resp \n";
$anotherURI    = URL;
$requestObject = HTTP::Request::Common::GET $anotherURI;
$result        = $ua->request($requestObject);
$resp          = $result->content;
#print $resp."\n";

我没有得到会话ID存储的位置以及如何获取它? 注意: - URL包含页面的URL。

2 个答案:

答案 0 :(得分:4)

我写了HTTP::CookieMonster来使这种事情变得更容易一些。如果你不知道你正在寻找哪个cookie,你可以这样做:

use strict;
use warnings;

use HTTP::CookieMonster;
use WWW::Mechanize;

my $mech    = WWW::Mechanize->new;
my $monster = HTTP::CookieMonster->new( $mech->cookie_jar );

my $url = 'http://www.nytimes.com';
$mech->get( $url );

my @all_cookies = $monster->all_cookies;
foreach my $cookie ( @all_cookies ) {
    printf( "key: %s value: %s\n", $cookie->key, $cookie->val);
}

如果你已经知道了cookie的密钥,你可以这样:

my $cookie = $monster->get_cookie('RMID');
my $session_id = $cookie->val;

答案 1 :(得分:1)

看看HTTP::Cookies->scan

这样的事情应该可以解决问题(至少应该在域上添加一个约束):

my $session_id;
$cookie_jar->scan(
    sub {
        my ($key,       $val,    $path,    $domain,  $port,
            $path_spec, $secure, $expires, $discard, $hash
        ) = @_;

        if ( $key eq "session_id" ) {
            $session_id = $val;
        }
    }
);