Perl學習筆記(十一)--發送http請求

    Perl發送http請求依賴於LWP模塊,模塊的安裝能夠使用ppm,也能夠去cpan下載後自行安裝。html

    #發送一個get請求:mysql

  

 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請求web

    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();獲取的是響應正文  

   這個是個完整的處理了sql

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";
}
相關文章
相關標籤/搜索