【PHP】CURL请求第三方API接口

当我们需要调用第三方接口时,就需要使用CURL,通过CURL操作去请求第三方API接口,有的是通过POST方式,有的是通过GET方式,下面介绍一个通用的使用CURL调用API接口的方法。

一、CURL操作

共两个方法,分别是CURL操作、JSON转数组

CURL操作:传入需要的参数,返回API接口的返回值

JSON转数组:一般接口返回的类型是json格式,为方便使用需要将json转换成数组格式

php 复制代码
/**
 * @describe CURL操作,支持POST和GET两种请求方式
 * @param $url:API接口请求地址,$param:请求参数,$ispost:请求方式 post=1/get=2
 * @return array  接口返回结果集
 */
public function freeApiCurl($url,$params=false,$ispost=0){
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'free-api' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , 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 );
    if ($response === FALSE) {
        return false;
    }
    curl_close( $ch );
    return $response;
}

/**
 * 将JSON内容转为数组,并返回
 */
public function returnArray($content){
    return json_decode($content,true);
}

二、调用示例

php 复制代码
$key = 'xxxxxx';
$apiUrl = 'https://restapi.amap.com/v3/ip';
$params = [
        "key" => $key,
        "ip" => $ip,
    ];
$params = http_build_query($params);    //系统函数,组装参数,形如key=xxxxxxx&ip=123.6.49.12

////////// GET方式请求 ////////////
$result = $this->returnArray($this->freeApiCurl($apiUrl,$params));

////////// POST方式请求 ////////////
$result = $this->returnArray($this->freeApiCurl($apiUrl,$params,1));
相关推荐
DICOM医学影像2 分钟前
2. go语言从零实现以太坊客户端-查询区块链账户余额
开发语言·golang·区块链·以太坊·web3.0·hardhat
Data_agent13 分钟前
Python 编程实战:函数与模块化编程及内置模块探索
开发语言·python
new_zhou13 分钟前
vs2019+qt工程中生成dump文件及调试
开发语言·qt·visual studio·dump调试
栈与堆38 分钟前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
一路向北·重庆分伦40 分钟前
03-01:MQ常见问题梳理
java·开发语言
txinyu的博客44 分钟前
结合游戏场景理解,互斥锁,读写锁,自旋锁,CAS / 原子变量,分段锁
开发语言·c++·游戏
阿里嘎多学长1 小时前
2026-01-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管
yuanyikangkang1 小时前
STM32 lin控制盒
开发语言
txinyu的博客1 小时前
HTTP服务实现用户级窗口限流
开发语言·c++·分布式·网络协议·http