繁体   English   中英

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

[英]how to pass variable to http post API in Perl?

我的摘要如下,我用谷歌搜索,找不到在引用的字符串中将变量传递给发布请求的解决方案。 大部分google结果只是将纯Json键值字符串对传递到帖子内容。 但是我需要将参数传递给内部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 } });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM