gpt4 book ai didi

Perl LWP :UserAgent how to I add headers?

转载 作者:行者123 更新时间:2023-12-01 08:52:15 28 4
gpt4 key购买 nike

我是一名新的 perl 程序员,试图使用 LWP:UserAgent 将 curl 请求转换为 Perl 脚本。

curl请求示例是:

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"

我的 PERL 等价物:
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",
);

结果 - HTTP::Response=HASH(0x27884bc)
这是添加标题的正确方法吗?

最佳答案

如果您想使用 LWP::UserAgent 使用自定义 header 进行 GET 请求,您可以将它们放入 $ua->get()顺便来电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.



您的示例缺少您发送请求的部分,因此很难说出您在做什么。

您的 @headers数组包含 header 和 URL 参数。这不会如你所愿。如果您想像这样构造 URL 和 header ,则需要一种不同的方法。

使用 URI module以编程方式创建 URI,然后使用 LWP::UA 的 get发送它,包括标题。
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
}

要输出完整的 HTTP::Response 对象,请使用 Data::Dumper .
use Data::Dumper;
print Dumper $res;

关于Perl LWP :UserAgent how to I add headers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38609198/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com