end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

LWP::UserAgentでリダイレクト先のコンテンツを取得

$res->is_redirect を使って、次のように書くみたい。

#!/usr/local/bin/perl
use strict;
use warnings;
use utf8;
use HTTP::Request::Common;
use LWP::UserAgent;

#↓今回の件とは関係ありませんが...
my $LWP_OPT =
    {file =>"cookies.txt",
     autosave=>1,
     ignore_discard => 1}; #expiresがないとcookieを保存しない為、これを無視
my $TEST_URL = 'https://hogehoge.jp/test';
my $MAX_REDIRECT = 10;

sub get_http_contents {
    my $ua = LWP::UserAgent->new;
    $ua->cookie_jar($LWP_OPT);

    my $req = POST( $TEST_URL,
                    [test_key_1 => 'test_val_1',
                     test_key_2 => 'test_val_2' ]);
    my $res = $ua->request($req);

    my $redirect_count = 0;
    while ( $res->is_redirect ) {	#requestを検知
	return undef $redirect_count++ > $MAX_REDIRECT;

	my $req = POST( $TEST_URL,
			[test_key_1 => 'test_val_1',
			 test_key_2 => 'test_val_2' ]);
        $res = $ua->request($req);
    }

    return $res;
}