Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get http and https return code in perl

Tags:

http

https

perl

I am new to perl and any help will be appreciated!!

I have to invoke some URLs through perl (On unix machine).URLs are both http and https

if URL gets invoked successfully,then its fine else create a log file stating that unable to invoke a URL.

For invoking the URL,I am thinking to use for e.g.

  exec 'firefox http://www.yahoo.com';

But how to get http and https request status code? Something like if status is 200,then ok else error..

Kindly help!!

like image 925
Sammidbest Avatar asked Jun 09 '26 10:06

Sammidbest


1 Answers

Rather than using a browser such a Firefox you should use an HTTP client library such as HTTP::Tiny or LWP::UserAgent.

For exmaple:

#!/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};
}

Which outputs:

alex@yuzu:~$ ./return_status.pl 
http://www.yahoo.com: 200
https://www.google.com: 200
http://nosuchsiteexists.com: 599

If you want to correctly recognise redirect status codes (3XX) you would have to set the max_redirect parameter to 0.

alex@yuzu:~$ perl -MHTTP::Tiny -E 'say HTTP::Tiny->new(max_redirect => 0)->get("http://www.nestoria.co.uk/soho")->{status};'
301

If all you care about is success then the response hashref contains a 'success' field which will be true on success and false on failure.

alex@yuzu:~$ perl -MHTTP::Tiny -E 'say HTTP::Tiny->new()->get("http://www.google.com")->{success};'
1
like image 198
Kaoru Avatar answered Jun 12 '26 08:06

Kaoru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!