Nicholas Anderson Nicholas Anderson - 3 months ago 37
Perl Question

Perl HTTP POST request with Content type and Authorization token

I need to send an HTTP POST request with the following HTTP headers:

Content-type: 'application/atom+xml'
Authorization: MyLogin auth=$token

The token is coming from an authorization subroutine. Here is the Perl making the actual request after the subroutine is successful:

my $ua = LWP::UserAgent->new;
my $req = $ua->post ( $url );
$req = header('Content-type' => 'application/atom+xml');
$req = header('Authorization' => "MyLogin auth=$token");

However, I receive the following error when run:

Undefined subroutine &main::header called ...

How can I accomplish this?


According to the LWP::UserAgent documentation, you can set additional headers by passing them as arguments to post:

my $ua = LWP::UserAgent->new;
my $response = $ua->post($url,
    'Content-type' => 'application/atom+xml',
    'Authorization' => "MyLogin auth=$token"

Note that $ua->post actually sends the request, so trying to set the headers after calling it, as you do in your example code, is useless. (Not to mention the fact that there is no header function in the main namespace unless you import it from somewhere or write it yourself.)