chris01
chris01

Reputation: 12331

Perl HTTP::Request - best way to parse the query-paramters

I get an object HTTP::Request out of a webserver if a request occurs. I only see GET-query-parameters in the URL or if it is from a POST in the header.

Is there a way HTTP::Request or any other package gives me these parameters in a nice way (e.g. a hash) and I do not need to parse it my myself?

e.g. GET http://example.net?a=3&b=jack

I'd like to access the value of a (= 3) and b (= jack) without parse it manually from the URL or the HTTP-Header (if POST).

Thanks!

EDIT

Thanks for the good advice about the package URI. It works perfectly for parameters in the URL.

But not for POST where the parameters are in the body. I adapted it for that.

if ($req->method eq "POST")      # $req is HTTP::Request
{           {
  my $uri = URI->new ("/whatever?" . $req->content);  # not very pretty
  %params = $uri->query_form ();
  ...

to get the same results. Do you think thats a good idea or is there a better - more straighter way??

Upvotes: 2

Views: 1073

Answers (2)

U. Windl
U. Windl

Reputation: 4325

Use URI::QueryString::query_form_hash like this (Perl debugger session):

  DB<2> use URI::QueryParam
  DB<4> use URI
  DB<5> $u = URI->new('http://server:52907/wsapi/decrypt/?otp=foobar')
  DB<6> x $u->query_param
0  'otp'
  DB<7> x $u->query_form_hash
0  HASH(0x27c75a8)
   'otp' => 'foobar'
  DB<9> x $u->path
0  '/wsapi/decrypt/'

Upvotes: 1

ikegami
ikegami

Reputation: 385849

use List::Util qw( pairs );   # Version 1.29+
use URI        qw( );

my $uri = URI->new( $request->uri );

# If none of the parameters can have multiple values.
# Usage: my $value = $params{$key};
my %params = $uri->query_form();

# If some of the parameters can have multiple values.
# Usage: my $value  = $params{$key}[0];
# Usage: my @values = @{ $params{$key} };
my %params;
for my $pair ( pairs $uri->query_form() ) {
   my ( $key, $value ) = @$pair;
   push @{ $params{$key} }, $value;
}

URI::QueryParam adds methods to $uri that appear to be convenient in this situation (query_param and query_form_hash), but are far too error-prone to use.

Upvotes: 2

Related Questions