javascriptperlhttp-request

Perl equivalent of a sample JavaScript codes


I have this code:

  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData
  })

I'd like to convert that into Perl, what I have so far is:

my $req = HTTP::Request->new( 'POST', 'https://graph.facebook.com/v2.6/me/messages');
$req->header( 'Content-Type' => 'application/json' );
$req->content( $messageData );

I not sure how I can incorporate the following line into my Perl code:

qs: { access_token: PAGE_ACCESS_TOKEN },

It specifies a query parameter to add to the URL.

I tried to search the net but most example either sends the json content or the query string but not both. I need something that can send both if my interpretation to the JavaScript code is correct.

Thanks in advance to anyone who will guide me.


Solution

  • You can use the URI module (possibly supplemented by the URI::QueryParam module) to build (and manipulate) a URL.

    use HTTP::Request::Common qw( POST );
    use JSON::XS              qw( encode_json );
    use URI                   qw( );
    
    my $message_data = encode_json(...);
    
    my $url = URI->new('https://graph.facebook.com/v2.6/me/messages');
    $url->query_form( access_token => PAGE_ACCESS_TOKEN );
    
    my $req = POST($url,
       Content_Type => 'application/json',
       Content      => $message_data,
    );