cdl*_*ary 13 perl uri escaping http
这个问题与在Perl中发出HTTP GET请求的最简单方法有什么关系?.
在通过LWP::Simple我发出请求之前,我有一个查询字符串组件的哈希值,我需要序列化/转义.编码查询字符串的最佳方法是什么?它应该考虑空格和需要在有效URI中转义的所有字符.我认为它可能在一个现有的包中,但我不确定如何找到它.
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);
Run Code Online (Sandbox Code Playgroud)
gpo*_*ojd 26
URI :: Escape可能是最直接的答案,正如其他人给出的那样,但我建议使用URI对象来完成整个事情.URI会自动为您转义GET参数(使用URI :: Escape).
my $uri = URI->new( 'http://example.com' );
$uri->query_form(foo => '1 2', bar => 2);
print $uri; ## http://example.com?foo=1+2&bar=2
Run Code Online (Sandbox Code Playgroud)
作为额外的奖励,LWP :: Simple的 get函数将获取URI对象作为其参数而不是字符串.
Leo*_*ans 18
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
URI比URI::Escape这简单得多.方法query_form()接受散列或hashref:
use URI;
my $full_url = URI->new('http://example.com');
$full_url->query_form({"id" => 27, "order" => "my key"});
print "$full_url\n"; # http://example.com?id=27&order=my+key
Run Code Online (Sandbox Code Playgroud)
使用模块URI来构建带有查询参数的URL:
use LWP::Simple;
use URI;
my $uri_object = URI->new('http://example.com/rest_api/');
$uri_object->query_form(spam => 'eggs', foo => 'bar baz');
$contents = get("$uri_object");
Run Code Online (Sandbox Code Playgroud)
我在这里找到了这个解决方案。
| 归档时间: |
|
| 查看次数: |
18122 次 |
| 最近记录: |