gpt4 book ai didi

perl - 如何将多部分/表单数据中的 HTTP POST 数据发送到 Perl 中的 REST API

转载 作者:行者123 更新时间:2023-12-05 01:07:52 25 4
gpt4 key购买 nike

我正在使用需要基本身份验证的 multipart/form-data 从我的 Perl 脚本向网站 REST API 发送 POST HTTP 请求。我将一些参数作为内容中的键值对与要上传的图像文件一起传递。我在带有编码的 header 中传递了凭据。来自 REST API 的响应是错误代码 422 数据验证。我的代码片段如下:

    use warnings;
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Headers;
use HTTP::Request;
use MIME::Base64;
use JSON;
use JSON::Parse 'parse_json';

my $url = 'https://api.xyxabc.org/objects';
my $imgmd5 = '3740239d74858504f5345365a1e3eb33';
my $file= "images/1839.png";

my %options = (
"username" => '___APIKEY___',
"password" => '' ); # PASSWORD FIELD IS TO BE SENT BLANK

my $ua = LWP::UserAgent->new(keep_alive=>1);
$ua->agent("MyApp/0.1 ");
my $h = HTTP::Headers->new(
Authorization => 'Basic ' . encode_base64($options{username} . ':' . $options{password}),
Content => [
'name'=> 'Ethereum',
'lang' => 'en',
'description' => 'Ethereum is a decentralized open-source',
'main_image' => $imgmd5,
'parents[0][Objects][id]' => '42100',
'Objects[imageFiles][0]' => $file,
'objectsPropertiesValues[142][ObjectsPropertiesValues][property_id]' => 142,
],
Content_Type => 'multipart/form-data',
);

my $r = HTTP::Request->new('POST', $url, $h);
my $response = $ua->request($r);
my $jp = JSON::Parse->new ();
print Dumper $response->status_line;
my $jsonobj = $response->decoded_content;
eval {
$jsonobj = $jp->parse ($jsonobj);
};
if ($@) {
print $@;
}
print Dumper $jsonobj;

错误是:

$VAR1 = '422 Data Validation Failed.';
$VAR1 = [
{
'field' => 'name',
'message' => 'Name cannot be blank.'
},
{
'message' => 'Language cannot be blank.',
'field' => 'lang'
}
];

我做错了什么?据我了解,基本上服务器没有得到格式良好的查询字符串和标题。我正在传递一些 32 个键值对以及要在实际脚本中上传的图像文件,我在这里制作了一个最小的脚本。我知道所有参数变量都很好,因为当我通过 postman 发布这个 HTTP 请求时,它会提示不同的错误。

我昨天晚上通过 postman 使用不同的参数值执行了类似的查询,并且它与上传的图像一起执行。但是现在 postman 和 Perl 脚本都在提示。我需要两件事:1.首先为什么通过 postman 的POST请求提示?2. 其次,我正在构建 Perl LWP 脚本以将数据上传到该网站的 REST API,我需要上面生成的功能脚本。

如果有人提供帮助,我将不胜感激。

最佳答案

使用 HTTP::Request::Common .从文档中引用:

The POST method also supports the multipart/form-data content used forForm-based File Upload as specified in RFC 1867. You trigger thiscontent format by specifying a content type of 'form-data' as one ofthe request headers. ...

文档中也有一个例子:

POST 'http://www.perl.org/survey.cgi',
Content_Type => 'form-data',
Content => [ name => 'Gisle Aas',
email => 'gisle@aas.no',
gender => 'M',
born => '1964',
init => ["$ENV{HOME}/.profile"],
]

关于perl - 如何将多部分/表单数据中的 HTTP POST 数据发送到 Perl 中的 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66829616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com