WWW ::机械化并不例如张贴JSON

问题描述:

我有以下代码:WWW ::机械化并不例如张贴JSON

my $j = encode_json { "arguments" => { "peer-port" => "4444" }, "method" => "session-set", }; 
$mech->get('http://192.168.1.10:9091'); 
my $req = HTTP::Request->new('POST', 'http://192.168.1.10:9091/transmission/rpc'); 
$req->header('Content-Type' => 'application/json'); 
$req->content($j); 
$mech->request($req); 

当它运行时,我得到以下错误:

Error POSTing http://192.168.1.10:9091/transmission/rpc: Conflict at ./pia.pl line 48. 

我无法找到任何东西这个特定的错误,我也无法在WWW :: Mechanize的文档(或HTTP :: Request的)中找到任何可以阐明它的东西。这个脚本在提交正确的表单时没有问题,它只在这个表单上失败(目标http服务器显然只接受ajax/json请求)。

“冲突”是从服务器的响应,你应该检查响应的细节。 从RFC2616:

10.4.10 409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. ...

因此,检查你得到充分的响应($mech->content)找出为什么发生了冲突。如果这无助于检查服务器端的日志或查阅服务器端API的文档。

在您的具体情况下,您可能需要在请求中添加X-Transmission-Session-Id标头,有关详细信息,请参见https://forum.transmissionbt.com/viewtopic.php?f=8&t=8393

您不需要明确创建HTTP::Request对象。

my $j = encode_json { "arguments" => { "peer-port" => "4444" }, "method" => "session-set", }; 
$mech->get('http://192.168.1.10:9091'); 
$mech->post("http://192.168.1.10:9091/transmission/rpc", 
    'Content-Type' => 'application/json', Content => $j); 
+2

这完全等价。这是一种风格建议,不是答案。 – ikegami 2014-10-01 11:41:12