Perl之HTTP::Request

本文介绍了使用Perl进行HTTP请求的多种方式,包括GET和POST请求,涉及LWP::UserAgent、HTTP::Request、HTTP::Headers等模块的使用,以及处理JSON、XML格式的数据,HTTPS请求、超时设置、URL编码、代理设置等相关内容。
摘要由CSDN通过智能技术生成

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 => { 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值