如何在perl中发布json数据

时间:2014-09-16 08:16:34

标签: json perl

我是Perl脚本的新手,然后遇到了如何为Web服务发布json数据的问题。我尝试了一个我在网上找到的模板perl脚本(用于测试)。但是,我遇到了一个问题,因为我看不到我要发布的预期数据。我不知道这个脚本是否有问题:

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"] } ';

$req->content($post_data);

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";
}

2 个答案:

答案 0 :(得分:0)

我们需要查看您获得的实际响应,以确定是否有问题。但是,HTTP::Request有一个方法as_string,可以为您提供请求的文字表示。

# ... stuff  
$req->content($post_data);

# show the request
print $req->as_string;

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

它将显示如下内容:

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

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

据我所知,这基本上是一个很好的要求。

答案 1 :(得分:-1)

这里的问题相同。在端点上我没有数据。 另一方面它的PHP和$ _POST仍然是空的。

#! /usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Cookies;
use JSON::XS;

my $url = 'http://myurl';

my $json = {'username' => 'foo' ,'password' => 'bar'};
my $req = HTTP::Request->new( 'POST', $url );
$req->header( 'Content-Type' => 'application/json' );
$req->content( encode_json $json );
my $lwp = LWP::UserAgent->new;
my $res = $lwp->request( $req );

$ req-> as_string是:

POST http://myurl
Content-Type: application/json

{"password":"bar","username":"foo"}

编辑: 这样做我想要的。在端点上,我们得到POST [' json']并可以将其解码为对象:

sub __POST {
    my ($self, $url,$obj) = @_;
    my $ua = LWP::UserAgent->new;
    $ua->cookie_jar( $self->{cookie} );
    my $res = $ua->post($url, { 'json' =>  encode_json $obj } );
    my $content  = $res->decoded_content();
    my $retval = eval { JSON::XS->new->utf8->decode($content); };
    if($@ || $retval->{code} != 200){
        return 0;
    }
    return 1;
}

Returnvalue也是一个JSON-String