lr. lr. - 1 year ago 123
JSON Question

How to post json data in perl

I'm new to Perl script and then got the problem on how to post json data for web service. I tried a template perl script I have found in the net (for testing). However, I had a problem since I cannot see the expected data that I will post. I don't know if something is wrong with this script:

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "https://domain/WebService/webservice.php";
# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');

$req->header('x-auth-token' => 'kfksj48sdfj4jd9d');

# add POST data to HTTP request body
my $post_data = '{ "value1" : "SMRT23489MER", "value2" : "7352009 ", "date" : "20140813", "time" : "2033", "info" : ["2424","324","545","565"] } ';


my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";

Answer Source

We would need to see the actual response you are getting in order to determine if something is wrong. However, HTTP::Request has a method as_string that will give you the textual representation of your request.

# ... stuff  

# show the request
print $req->as_string;

# ...
my $resp = $ua->request($req);

It will show something like this:

POST foo
Content-Type: application/json
X-Auth-Token: kfksj48sdfj4jd9d

{ "value1" : "SMRT23489MER", "value2" : "7352009 ", "date" : "20140813",
"time" : "2033", "info" : ["2424","324","545","565"] } 

Which is basically a fine request as far as I can tell.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download