如何在 Perl 中将变量传递给 http post API?
how to pass variable to http post API in Perl?
我的代码如下,我 googled 找不到将变量传递给的解决方案
我引用的字符串中的 post 请求。
大多数 google 结果只是将普通的 Json 键值字符串对传递给
post 内容。但是我需要将参数传递给内部 Json 值部分并调用相关的 REST api。有什么建议么?谢谢!
#!/usr/bin/perl -w
use strict;
use warnings;
# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");
# Create a request
my $req = HTTP::Request->new(POST => 'https://oapi.dingtalk.com/robot/send?access_token=foofb73f');
$req->content_type('application/json');
my $var1="value from var";
# works fine
my $message = '{"msgtype": "text","text":{"content":"plain string ok"}}';
# failed to compile
# my $message = '{"msgtype": "text","text":{"content":$var1}}';
$req->content($message);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line, "n";
}
您没有正确地将值转换为 JSON 字符串。
use Cpanel::JSON::XS qw( encode_json );
my $message = encode_json({ msgtype => "text", text => { content => $var1 } });
我的代码如下,我 googled 找不到将变量传递给的解决方案 我引用的字符串中的 post 请求。 大多数 google 结果只是将普通的 Json 键值字符串对传递给 post 内容。但是我需要将参数传递给内部 Json 值部分并调用相关的 REST api。有什么建议么?谢谢!
#!/usr/bin/perl -w
use strict;
use warnings;
# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");
# Create a request
my $req = HTTP::Request->new(POST => 'https://oapi.dingtalk.com/robot/send?access_token=foofb73f');
$req->content_type('application/json');
my $var1="value from var";
# works fine
my $message = '{"msgtype": "text","text":{"content":"plain string ok"}}';
# failed to compile
# my $message = '{"msgtype": "text","text":{"content":$var1}}';
$req->content($message);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line, "n";
}
您没有正确地将值转换为 JSON 字符串。
use Cpanel::JSON::XS qw( encode_json );
my $message = encode_json({ msgtype => "text", text => { content => $var1 } });