2016-09-06 7 views
0

ここでは、引数Perlを扱う際の私の問題があります。私はPerlファイルに与えられた引数があれば、httpリクエスト(Webサービス)にPerl引数の引数を渡す必要があります。LWP HTTPリクエストへのperlファイル引数の受け渡し

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

wsgrep.plファイルでは、上記の引数をhttp post paramsに渡す必要があります。

私は応答を得るためにこのURLのLWPパッケージを使用しています

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

、以下のように。

これを行うには良い方法がありますか?

更新

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

Insideは、私は与えられた引数からポストパラメータ部分を構築する必要があります。

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

この「wsgrep.pl」は何を使用していますか? – redneb

答えて

1

通常は、URLエンコードするためのparamsは、私は次のように使用したい:

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; 
+0

うわー!魅力のように動作します。ありがとうございます! – Raja

関連する問題