【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));
相关推荐
damoluomu4 天前
挑 PHP CMS 之前,先学会看它的协议
php
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超4 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int4 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger5 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读5 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
CCCCCCCCharlie5 天前
Linux进程控制四大核心操作
linux·开发语言