[英]How to set custom headers for HTTP::Tiny in Perl?
I'm having some trouble understanding the proper way to set headers for HTTP::Tiny
in Perl 5. So far I have seen examples of hashes, hash references, and a myriad of other seemingly incomposable ways.我在理解在 Perl 5 中为HTTP::Tiny
设置标头的正确方法时遇到了一些麻烦。到目前为止,我已经看到了散列、散列引用和无数其他看似不可组合的方法的示例。
What is the proper way of setting the headers for a request?为请求设置标头的正确方法是什么? What's an easy way to view the request before it is sent?在发送请求之前查看请求的简单方法是什么?
Here is some example code:下面是一些示例代码:
#!/usr/bin/env perl
use 5.12.1;
use HTTP::Tiny;
my $api_key = "::";
my %headers = (Authorization => sprintf 'Bearer %s', $api_key);
my $url = "https://api-fxpractice.oanda.com/v3/accounts";
my $response = HTTP::Tiny->new($url,
default_headers => {'Content-Type' => 'application/json'});
my $response = HTTP::Tiny->new->get($url, { default_headers => \%headers } );
print "$response->{status} $response->{reason}\n";
while ( my ( $k, $v ) = each %{ $response->{headers} } ) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
And it is giving me a 401.它给了我一个 401。
Thank you!谢谢!
Turns out the problem had a lot to do with me being stupid and not paying attention to the details.事实证明,这个问题与我愚蠢而不注意细节有很大关系。 Basically,基本上,
` `
my $api_key = "::"
my %headers = (
"Content-Type" => "application/json",
"Authorization" => sprintf 'Bearer %s', $api_key);
my $url = "https://api-fxpractice.oanda.com/v1/accounts";
my $response = HTTP::Tiny->new->get($url, { headers => \%headers } );
print "$response->{status} $response->{reason}\n";
while ( my ( $k, $v ) = each %{ $response->{headers} } ) {
for ( ref $v eq 'ARRAY' ? @$v : $v ) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
` `
hash means just %hash=(key=>value)
散列意味着只是%hash=(key=>value)
hash references means just $hashref={key=>value}
and this equal to $hashref=\\%hash;
散列引用仅表示$hashref={key=>value}
并且这等于$hashref=\\%hash;
So所以
$http = HTTP::Tiny->new( %attributes )
is just $http = HTTP::Tiny->new( %attributes )
只是
$http = HTTP::Tiny->new( attr1=>value1, ... )
And并且
$response = $http->get($url, \\%options)
is $response = $http->get($url, \\%options)
是
$response = $http->get($url, {attr1=>value1, ...} )
illustrative examples:说明性示例:
use HTTP::Tiny;
HTTP::Tiny->new->get($url);
HTTP::Tiny->new->get($url, { headers => { header1=>value1, header2=>value2 } };
# with headers set in one place
$handle=HTTP::Tiny->new( default_headers=>{h1=>3, h2=>4} );
$handle->get($url);
$handle->get($url, headers=>{ h2=>'overwrite' });
# without shorthand
HTTP::Tiny->new->request('GET', $url);
HTTP::Tiny->new->request('GET',$url, { headers => { header1=>value1, header2=>value2 } };
# post
HTTP::Tiny->new->request('POST',$url, { headers => { header1=>value1, header2=>value2 }, content=>'body to post' };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.