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

时间:2018-12-12 06:38:14

标签: spring perl curl optimization controller

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

为此,我要执行类似于:的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文件中。

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

任何线索都将有所帮助:)

3 个答案:

答案 0 :(得分:1)

作为再现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更为方便,因为您可以直接返回状态代码。

答案 1 :(得分:0)

不正确的做法,但使用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...."

也来自({How do I write a Perl script to use curl to process a URL?):

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

答案 2 :(得分:0)

如果只想在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等类似的标准方式。