如何使用 LWP::UserAgent 在 BOX API 中发出 post 请求? [英] How to make the post request in BOX API using LWP::UserAgent?

查看:159
本文介绍了如何使用 LWP::UserAgent 在 BOX API 中发出 post 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了以下代码

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 错误.并抛出

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

我不知道这是什么问题.与 Linux curl 相同的事情正在起作用.

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

推荐答案

Box API 文档说:

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

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

您的代码正在发送表单编码数据相反.

Your code is sending form-encoded data instead.

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

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

试试这个:

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

这篇关于如何使用 LWP::UserAgent 在 BOX API 中发出 post 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆