如何在 Perl 中编码 HTTP GET 查询字符串? [英] How do I encode HTTP GET query strings in Perl?

查看:49
本文介绍了如何在 Perl 中编码 HTTP GET 查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与在 Perl 中发出 HTTP GET 请求的最简单方法是什么?.

在通过 LWP::Simple 发出请求之前,我有一个需要序列化/转义的查询字符串组件的散列.对查询字符串进行编码的最佳方法是什么?它应该考虑空格和所有需要在有效 URI 中转义的字符.我认为它可能在现有包中,但我不知道如何找到它.

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

推荐答案

URI::Escape 做你想做的事.

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;
}

这篇关于如何在 Perl 中编码 HTTP GET 查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆