我写了一个小的PERL脚本来使用PERL从URL中获取一些数据。我不是一个经验丰富的程序员,我使用了Stackoverflow中的例子。但是,我总是得到答复
{“error”:{“code”:2,“message”:“post parameter request missing”}}
脚本看起来像这样
my $uri = 'URL';
my $json = '{"sourceCountry":"DE","sourceStore":476,"targetCountry":"DE","targetStore":[869],"article":[110101]}';
my $req = HTTP::Request->new( 'POST', $uri );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );
my $lwp = LWP::UserAgent->new;
$response = $lwp->request($req);
完整的答案如下:
HTTP/1.1 200 OK
Connection: close
Date: Wed, 15 Jan 2014 14:29:06 GMT
Server: Apache
Content-Length: 63
Content-Type: application/json; charset=utf-8
Client-Date: Wed, 15 Jan 2014 14:29:06 GMT
Client-Peer: 10.200.10.74:80
Client-Response-Num: 1
X-Powered-By: PHP/5.3.3
{"error":{"code":2,"message":"post parameter request missing"}}
我错了什么?
答案 0 :(得分:0)
尝试:
use HTTP::Request::Common 'POST';
my $lwp = LWP::UserAgent->new;
$lwp->request( POST $uri, 'Content-Type' => 'application/json', 'Content' => $json );
虽然除了设置Content-Length之外,基本上应该做同样的事情。
或者,如果您提到的错误字面上表明应该有一个名为request的POST参数(也称为表单数据参数),请尝试:
use HTTP::Request::Common 'POST';
my $lwp = LWP::UserAgent->new;
$lwp->request( POST $uri, [ 'request' => $json ] );
答案 1 :(得分:0)
假设您尝试联系的是JSON RPC 2服务,则表示您缺少部分结构。
my $json = '{
"jsonrpc":"2.0",
"id":1,
"method":"some-method",
"params":{"sourceCountry":"DE","sourceStore":476,"targetCountry":"DE","targetStore":[869],"article":[110101]}
}';
如果是JSON RPC服务,您可以使用JSON::RPC::LWP;它结合了LWP::UserAgent和JSON::RPC::Common。它使用Moose,因此需要安装很多依赖项。 (它使用Moose,因为JSON::RPC::Common使用Moose。)
use JSON::RPC::LWP;
my $url = ...;
my $rpc = JSON::RPC::LWP->new(
agent => 'Example ',
);
my $response = $rpc->call(
$url, # uri
'some-method', # service
{
sourceCountry => "DE",
sourceStore => 476,
targetCountry => "DE",
targetStore => [869],
article => [110101],
} # JSON container
);
if( my $error = $response->error ){
print 'error: #', $error->code, ' "', $error->message, "\"\n";
}else{
print "success!\n";
use Data::Dumper;
print Dumper( $response->result );
}
请注意,您没有为JSON::RPC::LWP提供JSON字符串,而是为其提供数据结构。