1

I have $cookie_jar which created using HTTP::Cookies:

$cookie_jar = HTTP::Cookies->new(
  file => "my$path/my_cookies.dat",
  autosave => 1,
);

I want to use this $cookie_jar using Mojo::UserAgent but didn't find an option, the only option I see is parsing raw string:

my $cookies = $cookie->parse($str);
brian d foy
  • 129,424
  • 31
  • 207
  • 592
jsor
  • 97
  • 5

2 Answers2

3

I've uploaded a new version of HTTP::Cookies::Mozilla and it includes a sample program that solves this issue.


Load your data using HTTP::Cookie then convert it whatever format that you like by calling scan with a callback:
$cookie_jar = HTTP::Cookies->new(
  file => "my$path/my_cookies.dat",
  autosave => 1,
);
$cookie_jar->scan( \&callback )

Inside that callback, convert it to the Mojo::Cookie::Response object:

{
my $jar = Mojo::UserAgent::CookieJar->new

# access the scoped variable after you've run all the callbacks.
sub jar { $jar }

sub callback {
    my( $version, $key, $val, $path, $domain, $port, 
        $path_spec, $secure, $expires, $discard, $hash ) = @_;

    my $cookie = Mojo::Cookie::Response->new;
    ...fill in data...

    $jar->add( $mojo_cookie);
    )
}

Alternately, write a subclass of HTTP::Cookies that reads your format the HTTP::Cookies way but populates a Mojo::CookieJar instead. It's not that hard (and I've written several such things, some of which are on CPAN).

HTTP::Cookies also has the as_string method which makes a multi-line string with one cookie per string. You can use those lines to feed into Mojo::Cookie to re-parse them, but that's not as appealing to me.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • 1
    I thought about the as_string method but it won't work, it creates a string in the same format it exports to, not in the format that would be expected from response data by other cookie jars. scan is probably the best bet. – Grinnz Jul 22 '19 at 15:54
1

They are not compatible objects, and nothing other than HTTP::Cookies can read the file it creates. You need to use a Mojo::UserAgent::CookieJar with Mojo::UserAgent. Note that it will create one by default, accessed via $ua->cookie_jar. It does not have file serialization support, but the Persistent role can add this functionality -- it still will not read the HTTP::Cookies format however.

Grinnz
  • 9,093
  • 11
  • 18
  • I see ,What i am trying to do is to use HTTP::Cookies::Mozilla which is a subclass of HTTP::Cookies to copy all my Firefox cookies to mojo::cookies and use them with Mojo::UserAgent , what is the fast solution to do this ? – smith Jul 22 '19 at 15:46