Perl之HTTP::Request

use URI::Escape;#URL编码

use JSON;

 

#发送GET请求

use LWP::Simple;

 

my $tmp = "您本次操作的验证码为:$code";

my $smsmsg = uri_escape_utf8($tmp); #URL编码

my $args="http://xxx?p=".$phone."&c=$smsmsg";

my $response = get($args);

 

或者:

use HTTP::Request;

use HTTP::Headers;

use LWP::UserAgent;

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

$ua->timeout(10); #设置超时时间10s, 默认是180s

my $header = HTTP::Headers->new( Content_Type => 'text/html; charset=utf8', ); #设置head

$request = HTTP::Request->new('GET', $url, $header);

my $response = $ua->request($request);

my $res = "";

if ($response->message ne "OK" && $response->is_success ne "1") { #出错,或者timeout了

    $res = "error or timeout";

} else {

    $res = decode("utf-8",$response->content);

}

 

 

#发送POST请求

use HTTP::Request;

use HTTP::Headers;

use LWP::UserAgent;

use JSON;

 

my $url="http://xxx?p=".$phone."&c=$smsmsg";

my $json = JSON->new();

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

my $req = HTTP::Request->new('POST', $url); 

my $response = $ua->request($req);

my $ret = $json->decode($response->decoded_content());

 

#复杂点的,PSOT内容为xml格式,请求为https

my $request_xml = create_xml_data($tmp); #构造 xml格式的字符串

my $header = HTTP::Headers->new( Content_Type => 'text/xml; charset=utf8', );

my $http_request = HTTP::Request->new( POST => "https://xxx", $header, $request_xml);

my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0x00 });

my $response = $ua->request($http_request);

 

# PSOT内容为JSON格式

my $header = HTTP::Headers->new( Content_Type => 'application/json; charset=utf8', );

my $param_json_str =$json->encode($post_data); #构造JSON格式的字符串

my $http_request = HTTP::Request->new( POST => "https://xxxxx", $header, $param_json_str );

 

#特殊POST, https服务器需要客户端上传证书

#以微信现金红包发放API为例,https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3

#证书说明:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3

#

my $header = HTTP::Headers->new( Content_Type => 'text/xml; charset=utf8', );

my $http_request = HTTP::Request->new( POST => "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", $header, $request_xml);

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

  ssl_opts => { 

你可能感兴趣的:(Perl,Perl)