PERL进行HTTP 调用 并设置消息头
测试版本
[root@justswitch-64 home]# perl -v
This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi
POST调用
#!/usr/bin/perl -w
use Data::Dumper;
use LWP::Simple;
use Encode qw/encode decode/;
use strict;
use MIME::Base64;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use LWP::UserAgent;
use JSON;
use utf8;
my $ua = LWP::UserAgent->new(env_proxy => 1,
keep_alive => 1,
timeout => 10);
my $url = "http://xxxx/api/xxx";
my $data="afdfsdf";
my $base64_data = encode_base64($data);
$base64_data=substr($base64_data,0,length($base64_data)-1);#base64 出来的字符串末尾有个回车符
$base64_data = encode_base64($base64_data);
$base64_data=substr($base64_data,0,length($base64_data)-1);#base64 出来的字符串末尾有个回车符
my $urlparam = "{\"id\":\"123456\",\"data\":\"".$base64_data."\"}";
print($urlparam."\n");
my $req = HTTP::Request->new(POST => $url);
$req->content_type("application/json");
$req->content($urlparam);
my $response = $ua->request($req);
my $resl = $response->content();
#print($resl."\n");
#将返回值json解码为hash结构
my $data = decode_json($resl);
my $resl_dumper = Dumper($data);
if ("ok" eq ${$data}{"status"})
{
print("call htttp ok\n");
}
else
{
print("call htttp failed\n");
}
GET 调用
my $req = HTTP::Request->new(POST => $url);
替换成
my $req = HTTP::Request->new(GET => $url);