Perl LWP:UserAgent how to I add headers?

Talgarth picture Talgarth · Jul 27, 2016 · Viewed 12.1k times · Source

I'm a new perl programmer trying to convert a curl request into a Perl script get using LWP:UserAgent.

The curl request example is:

curl -X GET -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Cache-Control: no-cache" -H "Postman-Token: eb3955f1-a7b5-65d7-f5c0-808c7aba6cef" "https://10.51.10.26/10/download?startTime=1461698250&endTime=1461698252&cNat=True&cNatShowDst=True&tuplesFile=True&summarizeTuples=False"

And my PERL equivalent:

use LWP::UserAgent;
my $browser = LWP::UserAgent->new;
my $url = 'https://10.51.10.26/10/download';
my @headers = (
   "startTime" => $queryStart, 
   "endTime" => $queryEnd, 
   "cNat" => "True", 
   "cNatShowDst" => "False", 
   "tuplesFile" => "False", 
   "summarizeTuples" => "False",
   "Authorization" => "Basic YWRtaW46YWRtaW4",
   "Cache-Control" => "no-cache", 
   "Postman-Token" => "eb3955f1-a7b5-65d7-f5c0-808c7aba6cef", 
);

Results in - HTTP::Response=HASH(0x27884bc)

Is this the correct way of adding headers?

Answer

simbabque picture simbabque · Jul 27, 2016

If you want to do a GET request with custom headers with LWP::UserAgent, you can put them into the $ua->get() call in the way the documentation describes.

This method will dispatch a GET request on the given $url. Further arguments can be given to initialize the headers of the request. These are given as separate name/value pairs. The return value is a response object. See HTTP::Response for a description of the interface it provides.

Your example is missing the part where you are sending the request, so it's hard to tell what you are doing.

Your @headers array contains both headers and URL params. That's not going to do what you expect. If you want to construct the URL and the headers like this, you need a different approach.

Use the URI module to create the URI programmatically, then use LWP::UA's get to send it including the headers.

use strict;
use warnings;
use LWP::UserAgent;
use URI;

my $uri = URI->new('https://10.51.10.26/10/download');
$uri->query_form(
    "startTime"       => $queryStart, # these two need 
    "endTime"         => $queryEnd,   # to be set above
    "cNat"            => "True", 
    "cNatShowDst"     => "False", 
    "tuplesFile"      => "False", 
    "summarizeTuples" => "False",   
);

my $ua = LWP::UserAgent->new;
my $res = $ua->get(
    $uri,
    "Authorization" => "Basic YWRtaW46YWRtaW4",
    "Cache-Control" => "no-cache", 
    "Postman-Token" => "eb3955f1-a7b5-65d7-f5c0-808c7aba6cef", 
);

if ($res->is_success) {
    # do stuff with content
} else {
    # request failed
}

To output the full HTTP::Response object, use Data::Dumper.

use Data::Dumper;
print Dumper $res;