Sammidbest
Sammidbest

Reputation: 515

How to get http and https return code in 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!!

Upvotes: 3

Views: 4327

Answers (1)

Kaoru
Kaoru

Reputation: 1570

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

Upvotes: 6

Related Questions