【问题标题】:Pass perl file arguments to LWP HTTP request将 perl 文件参数传递给 LWP HTTP 请求
【发布时间】:2017-01-14 08:42:54
【问题描述】:

这是我处理参数 Perl 的问题。我需要将 Perl 参数参数传递给 http 请求(Web 服务),无论给 perl 文件的参数是什么。

perl wsgrep.pl  -name=john -weight -employeeid -cardtype=physical

在 wsgrep.pl 文件中,我需要将上述参数传递给 http post 参数。

如下图,

http://example.com/query?name=john&weight&employeeid&cardtype=physical. 

我正在为这个 url 使用 LWP 包来获得响应。

有什么好的方法可以做到这一点吗?

更新: wsgrep.pl 里面

my ( %args, %config );

my $ws_url =
"http://example.com/query";

my $browser  = LWP::UserAgent->new;
# Currently i have hard-coded the post param arguments. But it should dynamic based on the file arguments. 
my $response = $browser->post(
    $ws_url,
    [
        'name' => 'john',
        'cardtype'  => 'physical'
    ],
);

if ( $response->is_success ) {
    print $response->content;
}
else {
    print "Failed to query webservice";
    return 0;
}

我需要从给定的参数构造后参数部分。

[
            'name' => 'john',
            'cardtype'  => 'physical'
        ],

【问题讨论】:

  • 你用的是什么wsgrep.pl

标签: perl perl-module lwp lwp-useragent


【解决方案1】:

通常,要对参数进行 url 编码,我会使用以下内容:

use URI;

my $url = URI->new('http://example.com/query');
$url->query_form(%params);

say $url;

您的需求更加精细。

use URI         qw( );
use URI::Escape qw( uri_escape );

my $url = URI->new('http://example.com/query');

my @escaped_args;
for (@ARGV) {
   my ($arg) = /^-(.*)/s
      or die("usage");

   push @escaped_args,
      join '=',
         map uri_escape($_),
            split /=/, $arg, 2;
}

$url->query(@escaped_args ? join('&', @escaped_args) : undef);

say $url;

【讨论】:

  • 哇!奇迹般有效。谢谢楼主!
猜你喜欢
  • 2018-02-27
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
相关资源
最近更新 更多