perllwp-useragent

LWP::UserAgent loses content data when redirecting via POST


I am posting JSON data to Jira, and the request is hitting CAS first. A series of redirects occur. However, after the initial request I noticed that the content is zeroed out on the first redirect. The end result is that my request reaches Jira with empty content and is unsucessful.

Short of preventing LWP::UserAgent from redirecting and following the links myself, I'm not sure what else to try. My understanding is that this is supposed to be handled by the module.

This is vaguely representative with redactions...

use LWP::UserAgent ();
use HTTP::Request ();
use HTTP::Headers;
use HTTP::Cookies;

my $cookie_jar = HTTP::Cookies->new();
my $user_agent = LWP::UserAgent->new;
$user_agent->cookie_jar( $cookie_jar );

push @{ $user_agent->requests_redirectable }, 'POST';

$user_agent->ssl_opts( $ssl_cert_file_pem );
$user_agent->ssl_opts( $ssl_key_file_pem );
$user_agent->ssl_opts( $verify_hostname );
$user_agent->timeout( $timeout );

my $headers_obj = HTTP::Headers->new;
$headers_obj->header( 'Accept' => '*/*' );
$headers_obj->header( 'Accept-Encoding' => 'gzip, deflate, br' );
$headers_obj->header( 'Accept-Language' => 'en-US' );
$headers_obj->header( 'Connection' => 'Keep-Alive' );
$headers_obj->header( 'Host' => $host );

my $http_request_obj = HTTP::Request->new;
$http_request_obj->method( $method );
$http_request_obj->uri( $uri );
$http_request_obj->content_type( 'Content-Type' => 'application/json' );
$http_request_obj->content( $content );

$user_agent->default_headers( $headers_obj );

$response_obj = $user_agent->request( $http_request_obj );

When I dump the response, I can see that the initial request returns a 302 which is then followed successfully... it's just that the content does NOT go with each redirect. How can I get LWP::UserAgent to forward content on redirect?


Solution

  • This is appropriate behaviour for a 302 response.

    What RFC 7231, the current HTTP spec, says the following about 302 responses:

    Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

    When LWP receives a 302 response to a POST made redirectable, it follows up with a GET request (which necessarily doesn't include the POST data of the original request).