【问题标题】:How to make the post request in BOX API using LWP::UserAgent?如何使用 LWP::UserAgent 在 BOX API 中发出 post 请求?
【发布时间】:2017-08-03 13:54:10
【问题描述】:

我试过下面的代码

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

【问题讨论】:

  • true'true' 不是同一个意思。 [ ... ]{ ... } 不可互换。
  • @SinanÜnür [ ]{ } 在使用 LWP 发布表单数据时几乎可以互换。
  • @melpomene 您假设接收方的软件不关心指定参数的顺序。不太可能,当然,但并非不可想象。

标签: perl rest lwp


【解决方案1】:

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

【讨论】:

  • 谢谢。从很长一段时间我都在努力。实际上,我想要使用 PHP 的解决方案,所以我在 PHP 标记中使用了相同的 question,但我没有得到结果。但解码后它正在工作,谢谢。
猜你喜欢
  • 2013-10-09
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多