Perl programmer for hire: download my resume (PDF).
John Bokma's Hacking & Hiking

Redirecting a POST as GET in Perl

April 28, 2017

Today, while testing a Perl implementation of a module to use a web based API, I bumped into the fact that LWP redirects a POST request as another POST request, when enabled. The web based API, though, insisted on a GET request.

After some reading of the LWP documentation I came up with the following solution:

my $ua = LWP::UserAgent->new();

$ua->add_handler(
    'response_done',
    sub {
        my $response = shift;
        $response->code() == 301 or return;

        my $req = $response->request();
        if ( $req->method() eq 'POST' ) {
            # Change redirect to a GET request with zero content
            $req->method( 'GET' );
            $req->content( '' );
            $req->headers()->remove_header('Content-Length');
        }
    return;
    }
);

When the response to the first request is done it verifies is the status code is 301 (redirect) and if the method is a POST. If this is the case the method is changed into GET, the original POSTed content set to nothing, and the Content-Length header removed.