如何使用LWP :: UserAgent在BOX API中发布post请求?

时间:2017-08-03 13:54:11

标签: perl rest lwp

我尝试过以下代码

my $url = "https://api.box.com/2.0/users/";

use strict;
use warnings;

use LWP::UserAgent; 
use HTTP::Request::Common qw{ POST };
use CGI;

my $ua      = LWP::UserAgent->new();
my $request = POST( $url, [ 'name' => 'mkhun', 'is_platform_access_only' => 'true',"Authorization" => "Bearer <ACC TOK>" ] );
my $content = $ua->request($request)->as_string();

my $cgi = CGI->new();
print $cgi->header(), $content;

上面的代码总是给出400错误。并抛出

{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"invalid_parameter","name":"entity-body","message":"Invalid value 'is_platform_access_only=true&Authorization=Bearer+WcpZasitJWVDQ87Vs1OB9dQedRVyOrs6&name=mkhun'. Entity body should be a correctly nested resource attribute name\/value pair"}]},

我不知道这是什么问题。 Linux curl也是如此。

curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <TOKEN>" \
-d '{"name": "Ned Stark", "is_platform_access_only": true}' \
-X POST

1 个答案:

答案 0 :(得分:2)

Box API documentation says

  

请求正文数据和响应数据都格式化为JSON

您的代码正在发送form-encoded data

此外,看起来Authorization应该是HTTP标头,而不是表单字段。

请改为尝试:

use strict;
use warnings;

use LWP::UserAgent;
use JSON::PP;

my $url = "https://api.box.com/2.0/users/";
my $payload = {
    name => 'mkhun',
    is_platform_access_only => \1,
};

my $ua = LWP::UserAgent->new;

my $response = $ua->post(
    $url,
    Authorization => 'Bearer <TOKEN>',
    Content => encode_json($payload),
);