以前也没有接触过通过https来测试API接口的方法,今天工作中用到了,也实现了。总结一下:大致分以下几个部分:
1、增加 证书:利用PHP将证书加载到脚本中如下:
//加载证书的函数
function sslInit($ch){
//证书-start
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_CAINFO, './cert/ca_cert.pem');//根证书
curl_setopt($ch, CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch, CURLOPT_SSLCERT, './cert/client_cert.pem');//公钥
curl_setopt($ch, CURLOPT_SSLKEYTYPE,'PEM');//私钥文件格式
curl_setopt($ch, CURLOPT_SSLKEY,'./cert/client_key.pem');//私钥
curl_setopt($ch, CURLOPT_SSLKEYPASSWD,'111111');//私钥的密码
//证书-end
curl_setopt($ch, CURLOPT_COOKIEJAR,'./logs/cookie.txt'); //保存
curl_setopt($ch, CURLOPT_COOKIEFILE,'./logs/cookie.txt');//读取
return $ch ;
}
2、实现登录 通过加载证书来验证用户的合法性及签名是否正确
function login(){
//fengbo.xue@quanshi.com q111111
$xml_data = '<?xml version="1.0" encoding="utf-8"?>';
$xml_data .= '';
$xml_data .= 'XXXXXX@XX.COM';
$xml_data .= 'tester';
$xml_data .= '';
$url = 'https://XXX.XX.XX/login';
$header[] = "Content-type: text/xml";//定义content-type为xml
$ch = curl_init();
$ch = $this->sslInit($ch);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$response = curl_exec($ch);
//echo $response;
return $response ;
if(curl_errno($ch)) {
print_r(curl_error($ch));
}
curl_close($ch);
}
3、加载要测试的API
如:
function join($LshyID)
{
$xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
1
';
$url = 'https://xxx.xxx.xxx/join/SME-MEETING/'.$LshyID;
$header[] = "Content-type: application/xml";//定义content-type为xml
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
//证书-start
$ch=$this->sslInit($ch);
$response = curl_exec($ch);
return $response;
if(curl_errno($ch)) {
print_r(curl_error($ch));
}
curl_close($ch);
}
总结:又是一个三步曲。。。哈哈。。 自己发现写代码还挺好玩的。以前还真想走开发的路。
希望对正迷茫的朋友,正在查找这方面的测试资源的朋友一点指导。哈哈。。。