Perl: programmatically sets the POST parameter using REST :: Client module

I created a REST server and now I want to quickly test it with a Perl client using the REST :: Client module.

It works fine if I execute a GET Request (explicitly setting parameters in the URL), but I cannot figure out how to set these parameters in POST requests.

This is what my code looks like:

#!/usr/bin/perl use strict; use warnings; use REST::Client; my $client = REST::Client->new(); my $request_url = 'http://myHost:6633/my_operation'; $client->POST($request_url); print $client->responseContent(); 

I tried something similar to:

 $client->addHeader ('my_param' , 'my value'); 

But this is clearly wrong, since I do not want to set a predefined HTTP header, but a request parameter.

Thanks!

+6
rest post perl
source share
3 answers

This is pretty straight forward. However, you need to know what content the server expects. Usually it will be XML or JSON.

f.ex. this works with a server that can understand JSON in the second parameter if you tell it that it is in the header in the third parameter.

 $client->POST('http://localhost:3000/user/0/', '{ "name": "phluks" }', { "Content-type" => 'application/json'}); 
+5
source share

The REST module accepts the content parameter of the body, but I found that it works with the parameter string, you need to set the correct content type.

So, the following code works for me:

 $params = $client->buildQuery([username => $args{username}, password => $args{password}]); $ret = $client->POST('api/rest/0.001/login', substr($params, 1), {'Content-type' => 'application/x-www-form-urlencoded'}); 
+4
source share

I did not use the REST module, but, looking at the POST function, it accepts the parameter of the body content, try creating a parameter string and sending them to the functions

 $client->POST($request_url, "my_param=my+value"); print $client->responseContent(); 
0
source share

All Articles