Home > Net >  Is it possible to get the redirected URL with Mojo::UserAgent?
Is it possible to get the redirected URL with Mojo::UserAgent?

Time:07-01

I know I can have Mojo::UserAgent redirect like this:

my $ua  = Mojo::UserAgent->new->max_redirects(3);

but is it possible to somehow get the URL it lands on after all redirects?

CodePudding user response:

If you set your user-agent to redirect, you can get the chain of transactions with redirects. In each, look for the Location header.

Here's an example, using the Mojo Lite app I have in 3xx:

use v5.26;
use Mojo::UserAgent;

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

# from https://github.com/briandfoy/3xx
# running perl app.pl daemon

foreach my $max ( 1 .. 3 ) {
    $ua->max_redirects($max);
    my $tx = $ua->get('http://127.0.0.1:3000/three');
    say "$max redirects:\n\t",
        join "\n\t",
        map { $_->result->headers->location }
        $tx->redirects->@*;
    }

Here's the output:

1 redirects:
    http://127.0.0.1:3000/two
2 redirects:
    http://127.0.0.1:3000/two
    http://127.0.0.1:3000/one
3 redirects:
    http://127.0.0.1:3000/two
    http://127.0.0.1:3000/one
    http://127.0.0.1:3000/none
  • Related