Perl: Fetch data from a URL
I need a quick way to fetch JSON data from a URL. Using HTTP::Tiny
is the easiest way. You can call the function different ways depending on whether you only want the body, or if you want the HTTP status code as well:
my $json = get_url("https://domain.com/stats.json");
my ($html, $http_code) = get_url("https://domain.com/index.html");
sub get_url {
my $url = shift();
my $http = HTTP::Tiny->new(verify_SSL => 1, timeout => 5);
my $resp = $http->get($url);
my $body = $resp->{content};
my $status = $resp->{status};
my @ret = ($body, $status, $resp);
return @ret;
}
Tags: