服务端与服务端之间,也存在接口编程。
比如我们网站服务端,需要发送短信、发送邮件、查询快递等,都需要调用第三方平台的接口。
1、php中发送请求
① file_get_contents函数 :传递完整的url参数 通常是get请求,有返回值(地址中的输出)
② curl请求方式(PHP的curl函数库):php中比较规范的一种发送请求方式。
2、CURL函数库
Curl函数库的使用流程:
① 使用curl_init初始化请求会话
② 使用curl_setopt设置请求一些选项
③ 使用curl_exec执行,发送请求
④ 使用curl_close关闭请求会话
3、封装请求函数
封装一个函数用来发送curl请求
在app/api/common.php中封装一个函数curl_request
代码封装:app/api/common.php
if(!function_exists('curl_request'))
{
//使用curl函数库发送请求
function curl_request($url, $method='get', $params=[], $type='http')
{
//初始化请求
$ch = curl_init($url);
//默认是get请求。如果是post请求 设置请求方式和请求参数
if(strtolower($method) == 'post'){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
//如果是https协议,禁止从服务器验证本地证书
if(strtolower($type) == 'https'){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
//发送请求,获取返回结果
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
/*if(!$res){
$msg = curl_error($ch);
dump($msg);die;
}*/
//关闭请求
curl_close($ch);
return $res;
}
}
if (!function_exists('geturl')){ function geturl($url){ $headerArray =array("Content-type:application/json;","Accept:application/json"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray); $output = curl_exec($ch); curl_close($ch); $output = json_decode($output,true); return $output; } }
4、本地模拟测试
先准备好一个接口地址:用于请求调用
# 商品列表接口
http://high.one.com/api/goods/1/edit
再写一个方法,发送请求,调用之前准备好的接口
public function index()
{
$url = 'http://high.one.com/api/goods';
$output = curl_request($url);
dd($output);
}
测试结果:
访问:http://high.one.com/admin/curlTest
5、curl请求错误调试
curl_errno函数 返回错误码
curl_error函数 返回错误信息
if(!$res){
$msg = curl_error($ch);
dump($msg);die;
}