将cURL POST转换为Perl POST

时间:2018-12-04 15:36:49

标签: linux perl

我在将cURL请求转换为Perl时遇到问题。 FWIW,在IBM AIX 7.1上使用v5.10.1。

在cURL中:

curl -s -u $USER:$PWD --data '@mft.json' -H 'Content-Type: application/json' -X POST $EVENT_URL

在Perl中:

use LWP::UserAgent;
use Data::Dumper;

my $ua = LWP::UserAgent->new(); 


my $user = "aaa";
my $pwd = "bbb";
my $port = 7090;
my $domain = "my.site.com";
my $url = "http://".$domain.":".$port;
my $event_url = $url."/mftapp/rest/v1/events";
my $file = "mft.json";

$ua->credentials($domain.":".$port, 'default', $user, $pwd);

my $response = $ua->post($event_url, Content_Type => 'form-data', Content => [file => $file]
);

my $content = $response->as_string();

print ($content);

根据Content_Type的值,我得到不同的结果:

  • Content_Type =“ application / json”,错误请求400
  • Content_Type =“表单数据”,不受支持的媒体类型415
  • Content_Type =“ application / x-www-form-urlencoded”,不支持的媒体类型415

使用这些方法添加标题会破坏我的代码:

$ua->default_header('Content-Type' => 'application/json')

在request.pl第20行上无法通过包“ LWP :: UserAgent”找到对象方法“ default_header”。

1 个答案:

答案 0 :(得分:3)

function getNamesOfLegalDrivers(people) { var legalDrivers = []; for (var i in people) { if(people[i].age >= 16){ legalDrivers.push(people[i].name); } } return legalDrivers; } const examplePeopleArray = [ { name: 'John', age: 14 }, { name: 'Joey', age: 16 }, { name: 'Jane', age: 18 } ]; console.log(getNamesOfLegalDrivers(examplePeopleArray)); 并没有您认为的那样。您只是在向服务器发送垃圾,这就是为什么即使您告诉它正文为JSON(这是正确的选择)也显示“ Bad Request”的原因。

我建议添加Content => [file => $file]并使用

use Path::Tiny;

实际上将读取并发送$ua->post($event_url, Content_Type => 'application/json', Content => path($file)->slurp_utf8, ); 的内容。

相关问题