繁体   English   中英

如何从Perl脚本执行CURL命令?

[英]How to execute CURL command from a perl script?

我想在部署完成后立即对我的服务进行热身,否则,第一个遇到我的服务的人将面临很大的延迟。

为此,我想执行类似于curl的curl命令:

curl -v -H "Accept:text/x-html-parts,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" -H "Accept-Charset:UTF-8" -H "Accept-Encoding:identity" -H "Connection:Keep-Alive" -H "Via:HTTP/1.1 ShoppingArea" + + + something.. something....

该curl脚本将在部署过程中执行,并将调用我的服务的主spring控制器。

我想将此命令写在perl文件中。

但是我不太确定该怎么做!

任何线索将是有帮助的:)

作为再现curl在纯Perl中的作用的粗略原型(使用https://corion.net/curl2lwp.psgi ),您可以使用LWP :: UserAgent轻松地将Curl命令行转换为Perl脚本:

#!perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;


my $ua = LWP::UserAgent->new();
my $r  = HTTP::Request->new(
    'GET' => 'https://api.example.com/',
    [
        'Connection' => 'Keep-Alive',
        'Via'        => 'HTTP/1.1 ShoppingArea',
        'Accept' =>
'text/x-html-parts,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Charset'  => 'UTF-8',
        'Accept-Encoding' => 'identity',
        'Host'            => 'api.example.com:443',
        'User-Agent'      => 'curl/7.55.1',
    ],

);
my $res = $ua->request( $r, );


__END__

Created from curl command line
curl -v -H "Accept:text/x-html-parts,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" -H "Accept-Charset:UTF-8" -H "Accept-Encoding:identity" -H "Connection:Keep-Alive" -H "Via:HTTP/1.1 ShoppingArea" https://api.example.com/ 

这需要使用LWP :: UserAgent模块,因此进行外壳curl可能仍然是您更快的方法。 如果您需要对结果做出反应,例如在HTTP Error 500上发送错误邮件或在HTTP Error 4xx上发送其他通知,则使用纯Perl更为方便,因为您可以直接返回状态代码。

不好的做法,但是使用system (运行任意的shell代码):

system "curl -v -H 'Accept:text/x-html-parts,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Charset:UTF-8' -H 'Accept-Encoding:identity' -H 'Connection:Keep-Alive' -H 'Via:HTTP/1.1 ShoppingArea' + + + something.. something...."

同样,来自( 如何编写Perl脚本以使用curl来处理URL? ):

my $curl=`curl http://whatever`

如果只想在Perl脚本中使用特定的CURL。 我建议您使用反引号执行系统调用。

my $curlcomm = `curl -v -H "Accept:text/x-html-parts,text/html,application/xhtml+xml,applicatio/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" -H "Accept-Charset:UTF-8" -H "Accept-Encoding:identity" -H "Connection:Keep-Alive" -H "Via:HTTP/1.1 ShoppingArea" + + + something.. something....`

但是也可以使用LWP :: UserAgentLWP :: Curl等类似的标准方法。

暂无
暂无

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

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