简体   繁体   English

在Perl中将变量用于HTTP请求标头

[英]Using variable for HTTP request headers with Perl

I am trying to write a function to create HTTP requests (POST and GET mostly) in Perl. 我正在尝试编写一个在Perl中创建HTTP请求(主要是POST和GET)的函数。 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: 我通过使用变量来使所有事物保持通用,这样我就不必担心请求的类型,有效负载,标头等,但是HTTP :: Request-> header()似乎并不喜欢我的变量:

    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. 我尝试了几种不同的方法,使用push_header最接近我,但我意识到这可能不是最佳解决方案。 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. 我希望一些Perl专家会确切地知道我在做什么错。 I'm sure it's something to do with the format of the string I'm passing in. 我确定这与我传入的字符串的格式有关。

@headers = "'x-auth-token' => '$_token'"; @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. 您正在传递一个参数:一个包含Perl代码片段的字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM