简体   繁体   中英

Pass perl file arguments to LWP HTTP request

Here is my issue with handling argument Perl. I need to pass Perl argument argument to a http request (Webservice) whatever Argument given to the perl file.

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

In the wsgrep.pl file, i need to pass the above arguments to http post params.

like below,

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

I am using LWP Package for this url to get response.

Is there any good approach to do this?

Updated: Inside the 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;
}

I need to construct post parameter part from the given arguments.

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

Normally, to url-encode params, I'd use the following:

use URI;

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

say $url;

Your needs are more elaborate.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM