首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Perl脚本中实现自定义Curl身份验证

在Perl脚本中实现自定义Curl身份验证
EN

Stack Overflow用户
提问于 2016-07-22 11:06:32
回答 1查看 2K关注 0票数 1

我正在构建机器人应用程序,试图使用perl脚本来实现curl请求,我遇到的问题是授权。

简单的curl命令类似于。

代码语言:javascript
复制
curl \
  -H 'Authorization: Bearer VM2CKBMXI3AVX2GMYPLBMYFRW3RCHYXS' \
  'https://api.wit.ai/message?v=20160722&q='

我不喜欢使用Perl脚本中的system()调用,因为在用户和机器人之间会有很多来回。

我找到了这个库http://search.cpan.org/~szbalint/WWW-Curl-4.17/lib/WWW/Curl.pm

我正在搜索setopt函数,以便找出它接受哪个参数,因为我的问题是将授权参数放在命令中的什么位置。我找到了这个链接http://web.mit.edu/darwin/src/modules/curl/curl/perl/Curl_easy/easy.pm

我现在的脚本代码如下所示:

代码语言:javascript
复制
use strict;
use warnings;
use WWW::Curl::Easy;

my $curl = WWW::Curl::Easy->new;
my $Authorization="Authorization: Bearer VM2CKBMXI3AVX2GMYPLBMYFRW3RCHYXS";

$curl->setopt(CURLOPT_HEADER,1);
$curl->setopt(CURLOPT_URL, 'https://api.wit.ai/message?v=20160721&q=hello');

# A filehandle, reference to a scalar or reference to a typeglob can be used here.
my $response_body;
$curl->setopt(CURLOPT_WRITEDATA,\$response_body);

# Starts the actual request
my $retcode = $curl->perform;

# Looking at the results...
if ($retcode == 0) {
     print("Transfer went ok\n");
     my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     # judge result and next action based on $response_code
     print("Received response: $response_body\n");
} else {
     # Error code, type of error, error message
     print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."\n");
}

我只需要知道我应该使用哪个CURLOPT来实现授权。如果你有任何想法,那将是很棒的。

谢谢Eran Gross

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-22 11:49:38

如果您只想设置标题"Authorization“,则选项为CURLOPT_HTTPHEADER

代码语言:javascript
复制
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Curl::Easy;
my $curl = WWW::Curl::Easy->new;
$curl->setopt(CURLOPT_URL, 'http://127.0.0.1/dumprequest.php');
my @headers  = ("Authorization: keygoeshere", "X-Foo: Bah");
$curl->setopt(CURLOPT_HTTPHEADER, \@headers);
$curl->setopt(CURLOPT_HEADER, 1);
my $retcode = $curl->perform;

提供:

代码语言:javascript
复制
GET dumprequest.php HTTP/1.1
Host: 127.0.0.1
Accept: */*
Authorization: keygoeshere
X-Foo: Bah

但是如果你真的想做超文本传输协议的认证,那么你可以使用CURLOPT_USERPWDCURLOPT_HTTPAUTH。有关选项的更多信息,请参见https://curl.haxx.se/libcurl/c/curl_easy_setopt.html

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38517502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档