我對 Perl 相當陌生。(使用 Perl 5)需要呼叫需要 POST 請求的 REST API 端點,并且它只支持基本身份驗證。
我嘗試了以下邏輯,但我得到了:無法在 C:/Strawberry/perl/vendor/lib/HTTP/Message.pm 的無福參考上呼叫方法“克隆”
use strict;
use warnings;
use Encode qw(encode_utf8);
use HTTP::Request ();
use JSON::MaybeXS qw(encode_json);
#use REST::Client;
use MIME::Base64;
my $username = '';
my $password = '';
my $url = 'https://testapi.com/webapi/AddData';
#my $header = ['Content-Type' => 'application/json; charset=UTF-8'];
my $header = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};
my $data = {GroupName=> 'City', Member=> 'New York'};
my $encoded_data = encode_utf8(encode_json($data));
my $r = HTTP::Request->new('POST', $url, $header, $encoded_data);
print $r->responseContent();
我在這里的邏輯可能完全錯誤,但是我們如何使用 PERL 更正或構建正確的 Basic auth POST REST API 呼叫。
有問題的 API 接受以下格式的資料:
{
"GroupName": "City",
"Member": "New York"
}
如果呼叫成功,它將回傳以下我們需要“ReturnValue”資料的資料:
{
"IsPass": true,
"ReturnValue": "New city has been added"
}
編輯
通過調整標題邏輯得到這個作業:
my $header = ['Content-Type' => 'application/json; charset=UTF-8', 'Authorization' => 'Basic ' . encode_base64($username . ':' . $password)];
uj5u.com熱心網友回復:
您實際上還沒有發送請求。你剛剛構建了它。正如檔案所說:
my $r = HTTP::Request->new('POST', $url, $header, $encoded_data);
# at this point, we could send it via LWP::UserAgent
# my $ua = LWP::UserAgent->new();
# my $res = $ua->request($r);
此外,responseContent不存在于HTTP::Request和HTTP::Response(或 HTTP::Whatever)中。但是,它存在于REST::Client 中,您已將其注釋掉。
uj5u.com熱心網友回復:
試試這個,看看我的評論標記為 [Welcho]
use warnings;
use Encode qw(encode_utf8);
use HTTP::Request ();
use JSON::MaybeXS qw(encode_json);
#use REST::Client;
use MIME::Base64;
use LWP::UserAgent; # [Welcho] Add this
my $username = '';
my $password = '';
my $url = 'https://testapi.com/webapi/AddData';
#my $header = ['Content-Type' => 'application/json; charset=UTF-8'];
my $header = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};
my $data = {GroupName=> 'City', Member=> 'New York'};
my $encoded_data = encode_utf8(encode_json($data));
my $r = HTTP::Request->new('POST', $url, $header, $encoded_data);
# [Welcho] comment this print $r->responseContent();
#[Welcho]
my $ua = LWP::UserAgent->new();
my $res = $ua->request($r);
print $res->decoded_content;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312521.html
下一篇:使用PHP發送POST請求
