Search code examples
perlcookieslwp-useragentmojo-useragent

HTTP::Cookies to Mojo::UserAgent::CookieJar


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);

Solution

  • 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.