我是perl的新手,我们将不胜感激!
我必须通过perl调用一些URL(在Unix机器上).URL既是HTTP又是https
如果成功调用了URL,则可以创建一个日志文件,指出无法调用URL。
为了调用URL,我正在考虑将其用于
exec 'firefox http://www.yahoo.com';
但是如何获取http和https请求状态代码?如果状态为200,则可以,否则出现错误。
请帮助!
不要使用诸如Firefox之类的浏览器,而应使用HTTP客户端库,例如HTTP :: Tiny或LWP :: UserAgent。
例如:
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use HTTP::Tiny;
my $Client = HTTP::Tiny->new();
my @urls = (
'http://www.yahoo.com',
'https://www.google.com',
'http://nosuchsiteexists.com',
);
for my $url (@urls) {
my $response = $Client->get($url);
say $url, ": ", $response->{status};
}
哪个输出:
alex@yuzu:~$ ./return_status.pl
http://www.yahoo.com: 200
https://www.google.com: 200
http://nosuchsiteexists.com: 599
如果要正确识别重定向状态码(3XX),则必须将max_redirect
参数设置为0。
alex@yuzu:~$ perl -MHTTP::Tiny -E 'say HTTP::Tiny->new(max_redirect => 0)->get("http://www.nestoria.co.uk/soho")->{status};'
301
如果您只关心成功,则响应hashref包含一个“成功”字段,成功时为true,失败时为false。
alex@yuzu:~$ perl -MHTTP::Tiny -E 'say HTTP::Tiny->new()->get("http://www.google.com")->{success};'
1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句