如何在Perl中将变量传递给http post API?

如何在Perl中将变量传递给http post API?,perl,http,post,lwp,Perl,Http,Post,Lwp,我的代码片段如下所示,我在谷歌上搜索,无法找到将变量传递给的解决方案 我引用的字符串中的post请求。 大多数google结果只是将简单的Json键值字符串对传递给 发布内容。但是我需要将参数传递给内部Json值部分,并调用相关的RESTAPI。有什么建议吗?谢谢 #!/usr/bin/perl -w use strict; use warnings; # Create a user agent object use LWP::UserAgent; my $ua = LWP::UserAgen

我的代码片段如下所示,我在谷歌上搜索,无法找到将变量传递给的解决方案 我引用的字符串中的post请求。 大多数google结果只是将简单的Json键值字符串对传递给 发布内容。但是我需要将参数传递给内部Json值部分,并调用相关的RESTAPI。有什么建议吗?谢谢

#!/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 } });