perlhttpescapinguri

How do I encode HTTP GET query strings in Perl?


This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);

Solution

  • URI::Escape does what you want.

    use URI::Escape;
    
    sub escape_hash {
        my %hash = @_;
        my @pairs;
        for my $key (keys %hash) {
            push @pairs, join "=", map { uri_escape($_) } $key, $hash{$key};
        }
        return join "&", @pairs;
    }