Perl学习笔记(十一)--发送http请求

    Perl发送http请求依赖于LWP模块,模块的安装可以使用ppm,也可以去cpan下载后自行安装。

    #发送一个get请求:

  

 use LWP::UserAgent;
  $ua = LWP::UserAgent->new;
  $ua->agent("$0/0.1 " . $ua->agent);
  # $ua->agent("Mozilla/8.0") # pretend we are very capable browser

  $req = HTTP::Request->new(
     GET => 'http://www.baidu.com');
  $req->header('Accept' => 'text/html');

  # send request
  $res = $ua->request($req);
  print $res->decoded_content;

   #发送一个post请求(恩,抄的)

    use LWP::UserAgent;  
     my $ua = LWP::UserAgent->new;  
     my $req = HTTP::Request->new('POST' => 'http://localhost:8080/webtest/a.jsp');  
     $req->content_type('application/x-www-form-urlencoded');#post请求,如果有发送参数,必须要有这句  
     $req->header('Cookie' => "key1=value1;key2=value2"); #如果想发送cookie,则需这句  
     $req->header('Accept-Language' => 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3');#如需发送请求头,  #只需像这行代码一般  
     $req->content("name=zhangsan&id=123");#发送post的参数  
     my $res = $ua->request($req);  
     print $res->status_line."\n";  
     print $res->as_string();#获取的是原始内容,包括响应头,响应正文  
      #$res->content();获取的是响应正文  

   这个是个完整的处理了

use strict;
use encoding 'utf8',STDIN=>'utf8',STDOUT=>'gb2312';
use DBI;
use LWP;
#use LWP::UserAgent;
#use LWP::Simple;

my $url = 'https://xxxx.com';
my $host = 'xxxxds.aliyuncs.com';
my $username = 'ssss';
my $password = 'password';
my $database = 'dbdbdb';
my $dbport = '3306';
my $merchantId = '7';
my $identityid = 'userii179';
my $mobile = '13222229989';
my $posturl = $url."/riskportal/limit/buyer/v1.0/createAccount/$merchantId/$identityid/$mobile";
my $ua=LWP::UserAgent->new(timeout=>10);
#my @header=(
#	'Cookie'=>"",
#	'Accept-Charset'=>'utf-8',
#	'Accept-Language'=>'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3'
#	);
my $request=HTTP::Request->new(POST=>$posturl);
#$request->header('content-type'=>'application/json');
#$request->header(@header);
my $response=$ua->request($request);
my $responsestring=$response->decoded_content;
print "The response of process is #$responsestring#\n";
#my $content=$response->content;
#print $content;

#判断返回结果
if($responsestring=~/501/)
{
	print "501---shoujihaoyibangding\n";
}elsif($responsestring=~/200/)
{
	print  "200---zhengchang\n";
}else
{
	print "Don't know what to write";
}

#连接数据库
my $dbh=DBI->connect("DBI:mysql:database=$database;host=$host;port=$dbport",$username,$password,{'RaiseError'=>1});
$dbh->do("SET NAMES 'utf8'") or die "Can't set names". $dbh->errstr;

#查询数据
my $sth=$dbh->prepare("select * from t_risk_buyer where mobile=\'$mobile\'");
$sth->execute();
my @ary=$sth->fetchrow_array();
print $ary[1],$ary[2],$ary[3];
print "\n";
$sth->finish();

#比对数据
my $datecorrect = 1;
if($ary[1] eq $mobile)
{
	print "---shoujihao zhengque\n";
}else{
	print "---shoujihao cuowu\n";
	$datecorrect = 0;
}
$dbh->disconnect();

#比对结果判断
if($datecorrect eq 1)
{
	print "yonghu chuangjian chenggong \n";
}else{
	print "yonghu chuangjian shibai \n";
}

 

你可能感兴趣的:(Perl学习笔记(十一)--发送http请求)