如何在perl中发布json数据

如何在perl中发布json数据,json,perl,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

我不熟悉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";
}

我们需要看到您得到的实际响应,以确定是否有问题。但是,它有一个方法
作为_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"] } 

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

这里也有同样的问题。在端点上,我没有得到任何数据。 它的PHP在另一边,$\u 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_字符串为:

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字符串

当我想用Perl(或者浏览器之外的任何东西)检查HTTP请求的内容时,我倾向于使用Charles Proxy?你能把它贴在这里吗?总是
严格使用;使用警告!我建议使用-它内置了JSON编码和解码。@ialarmedalien,有时用作其后端,这越来越被视为有问题(JSON::XS有线程问题,并且没有公共bug跟踪器)。相反,我建议您看看(在过去几年中,Perl已经与Perl捆绑在一起了,所以您可能已经有了它),如果这证明太慢的话,(这是原始JSON::XS的一个分支)。