如何用php调用外部接口json数据?

主要用到了PHP中的 curl模块,分get和post两种方式。

<?php
/**
* Created by PhpStorm.
* User: dayue
* Date: 2017/12/4
* Time: 16:25
*/

namespace App\Services;


class ApiService
{
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);
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// dd($httpCode);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
// dd($httpInfo);
curl_close($ch);
$response = json_decode($response,true);
$result = [];
$result['httpCode'] = $httpCode;
$result['info'] = $response;
return $result;

// $data_string = json_encode($params);
//
// $ch = curl_init($url);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// 'Content-Type: application/json',
// 'Content-Length: ' . strlen($data_string))
// );
//
// $result = json_decode(curl_exec($ch), true);
//
// curl_close($ch);
// return $result;
}
}
 
//json接口测试用例
public function ApiTest()
{
$url = 'http://ip.taobao.com/service/getIpInfo.php';
$params = 'ip=101.81.71.12';
$res = ApiService::reqUrl($url, $params);
return $res['info']['data'];
}
JSON API免费接口
posted @ 2017-12-04 17:58  hypnot  阅读(3303)  评论(0编辑  收藏  举报