PHP 调用外部接口
2024-10-21 13:23:59
//1.类中定义静态方法 class FtpService{ /**
* 请求外网
* @param $url 外网接口url
* @param bool $params 参数,拼接字符串 post请求可以为数组
* @param int $ispost 是否是post请求
* @return array|bool
*/
public static function reqUrl($url, $params = false, $ispost = 0)
{
$httpInfo = array();
$ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Data');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
} $response = curl_exec($ch);
//echo $response; //打印查看数据
if ($response === FALSE) {
return false;
} $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
$response = json_decode($response,true); $result = [];
$result['httpCode'] = $httpCode;
$result['info'] = $response;
return $result;
} } //2.调用eg: (例子为post请求,参数为数组或者拼接字符串) //post调用 参数为数组
public function ApiTestPost()
{
$url = config('http_host')['interface']; //配置外网接口
$data = [
'code'=>0,
'sign'=>'1223435', //校验签名,自己设置签名规则 外网校验
'ordser_sn'=>'1234567'
];
//$data = 'code=0&sign=12345&order_sn=1234567'; //也可以是这种格式
$res = $this->reqUrl($url, $data,1);
return $res['info']['data'];
} //get调用 参数为拼接字符串 public function ApiTest()
{
$url = config('http_host')['interface']; //配置外网接口 $url = 'baidu.com'
$order_sn = "987654321";
$sign = '1234566';
$params = "&appoint_sn=".$appoint_sn.'&sign='.$sign;
$res = $this->reqUrl($url, $params);
return $res['info']['data'];
} //3.外网接口部分获取参数:
post请求中:$data = input(''); //得到的就是上面$data数据 校验签名后写逻辑部分就ok了
get请求中: $order_sn = input('order_sn');
$url = 'baidu.com'
https://www.cnblogs.com/luqiangblogs/p/14031152.html
最新文章
- 机器学习实战笔记(Python实现)-00-readme
- Windows Server 2008 R2 组策略基本设置
- Syslog-ng
- HDOJ-ACM1021(JAVA)
- 从Qt4到Qt5的,主要的进化有三(对于QtWidget的精简和优化会很有限)
- java关键字中文对比
- 关于Cesium中的常用坐标系及说明
- bzoj1858[Scoi2010]序列操作 线段树
- functools 之 partial(偏函数)
- 痞子衡嵌入式:忘掉cmd.exe吧!选用优雅的控制台终端(ConsoleZ)
- HeapByteBuffer与DirectByteBuffer
- c 语言 随机数选取6个数 一定范围内
- C# 关闭子窗体释放子窗体对象问题
- C#使用七牛云存储上传下载文件、自定义回调
- 简单的js动态显示当前时间
- 【python】 Windows下pip安装包报错:Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat
- Java运行Python脚本的几种方式
- 【AR实验室】mulberryAR :添加连续图像作为输入
- Clustering Factor——索引的成本指标
- Major OSL changes to catch up