How to make the post request in BOX API using LWP::UserAgent?

拟墨画扇 提交于 2019-12-11 05:08:47

问题


I have tried the following code

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;

The above code always give the 400 error. And throwing the

{"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"}]},

I don't know what is the issue. The same thing with Linux curl is working.

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

回答1:


The Box API documentation says:

Both request body data and response data are formatted as JSON.

Your code is sending form-encoded data instead.

Also, it looks like Authorization is supposed to be an HTTP header, not a form field.

Try this instead:

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),
);


来源:https://stackoverflow.com/questions/45486313/how-to-make-the-post-request-in-box-api-using-lwpuseragent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!