Question

How to load cookies from file in Mojo like this code:

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

if (-e "cookie.txt") {
    print q[Cookie file: cookie.txt found!\n];

    $mech->cookie_jar(HTTP::Cookies->new(
        file => q[cookie.txt],
    ));

    $mech->get(qq[$cfg->{'url'}/login]) or die qq[invalid request\n];
} else {
    print q[Cookie file: cookie.txt NOT found!\n];

    $mech->get(qq[$cfg->{'url'}/login]) or die qq[invalid request\n];

    $mech->submit_form(
        form_name => 'login',
        fields => {
            'email'     => $cfg->{'email'},
            'password'  => $cfg->{'password'},
        },
    );
    die qq[ERROR: Failed to login!\n] unless ($mech->success);

    $mech->cookie_jar->save("cookie.txt");
}

Unless there cookie.txt, the script uses the username and password, and the resulting cookies saved in the file cookie.txt and the next time using this file.

I'm trying to rewrite this code without using Mechanize and i have a problem with saving and loading a cookie file.

my $ua = Mojo::UserAgent->new;
$ua->cookie_jar(Mojo::CookieJar->new);
and then I do not know how to continue :)

P.S. Sorry for my english and perl :)

Was it helpful?

Solution

As I know, Mojolicious does not support this feature, but you can use store and retrive functions of the Storable module this way:

use Mojo::Base -strict;

# uncomment to be sure
#BEGIN { $ENV{MOJO_USERAGENT_DEBUG} = 1; }

use Mojo::UserAgent;
use Storable;

my $cookie_path = 'my.cookie';
my $req_str     = 'http://www.google.com/';


SAVE: {
  my $ua1 = Mojo::UserAgent->new;
  $ua1->get($req_str);
  store $ua1->cookie_jar, $cookie_path;
}

my $ua2 = Mojo::UserAgent->new;

# load
$ua2->cookie_jar(retrieve($cookie_path));

# make a request with loaded cookie
$ua2->get($req_str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top