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

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

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.