當我們需要調用第三方接口時,就需要使用CURL,通過CURL操作去請求第三方API接口,有的是通過POST方式,有的是通過GET方式,下面介紹一個通用的使用CURL調用API接口的方法。
一、CURL操作
共兩個方法,分別是CURL操作、JSON轉數組
?CURL操作:傳入需要的參數,返回API接口的返回值
JSON轉數組:一般接口返回的類型是json格式,為方便使用需要將json轉換成數組格式
/*** @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);
}
二、調用示例
$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));