-1

I am trying to write a function to create HTTP requests (POST and GET mostly) in Perl. I am keeping everything generic by using variables so that I don't have to worry about the type of request, the payload, headers, etc, however HTTP::Request->header() doesn't seem to like my variable:

    my($req_type, $headers, $endpoint, $args, $request, $jsonfile) = @_;
    my $ua = LWP::UserAgent->new;
    my $req = HTTP::Request->new($req_type => $endpoint);
    $req->content_type('application/json');

    foreach (@$headers) {
        $req->push_header($_);
    }

    $req->content($args);
    $req->content($request);

    print "request : ".$req->as_string;

I tried a few different approches, and using push_header got me the closest, but I realize it may not be the best solution. I think it might have something to do with single quotes getting passed in:

@headers = "'x-auth-token' => '$_token'";

I can post more of the code if it is helpful. I'm hoping some Perl guru will know exactly what I'm doing wrong. I'm sure it's something to do with the format of the string I'm passing in.

user3270760
  • 1,444
  • 5
  • 23
  • 45
  • Why are you passing your headers as strings rather than a hash or an array? – jcaron Dec 15 '15 at 13:57
  • Lack of experience mostly... I thought I was passing them with an array? – user3270760 Dec 15 '15 at 14:00
  • `"'x-auth-token' => '$_token'"` is a string. An array would be `('x-auth-token' => $_token)`. An array ref would be `['x-auth-token' => $_token]` – jcaron Dec 15 '15 at 14:07
  • Do you have `$headers`, which is a scalar, or `@headers`, which is an array? It's impossible to give you an answer to this question without seeing your inputs. – Matt Jacob Dec 15 '15 at 14:10
  • Ok I added the input to the code. It's coming in as `$headers` and the foreach loop is actually printing the strings from the array, but it doesn't seem right. – user3270760 Dec 15 '15 at 14:15
  • OK... but what does `$headers` contain? – Matt Jacob Dec 15 '15 at 14:30
  • @MattJacob $headers contains `(x_auth_token => $_token, accept => 'application/json');` The solution below worked for me. Was this question really considered "unclear" or "not useful" enough to warrant a down vote? – user3270760 Dec 15 '15 at 16:36
  • @user3270760 Considering that the answer to the question is completely dependent on the contents of that variable, absolutely. Please learn how to create a [mcve], and also [ask] a good question. – Matt Jacob Dec 15 '15 at 16:41

1 Answers1

3

@headers = "'x-auth-token' => '$_token'";

The header function expects to be passed two arguments. The header name and the header value.

You are passing it one argument: a string containing a fragment of Perl code.

You need to format your data more sensibly.


my %headers = (
    "x-auth-token" => $_token;
);

and

foreach my $header_name (keys %headers) {
    $req->push_header($header_name => $headers{$header_name});
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335