Searched for tag fetch and found 1 results in 0.4 ms

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();

    require HTTP::Tiny;
    my $http = HTTP::Tiny->new(verify_SSL => 1, timeout => 5);
    my $resp = $http->get($url);

    my $body   = $resp->{content} // "";
    my $status = $resp->{status}  // -1;

    if (wantarray()) {
        my @ret = ($body, $status, $resp);
        return @ret;
    } else {
        return $body;
    }
}
Tags:
Leave A Reply