zoukankan      html  css  js  c++  java
  • 如何用php调用外部接口json数据?

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

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

    namespace AppServices;


    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免费接口
    闲静少言,不求达内。乐于技,喜刨根,不求甚解;每有会意,其乐无穷。
  • 相关阅读:
    《剑指offer》第十二题(矩阵中的路径)
    《剑指offer》第十五题(二进制中1的个数)
    《剑指offer》第十题(斐波那契数列)
    《剑指offer》第十一题(旋转数组的最小数字)
    原始的生成对抗网络GAN
    《剑指offer》第九题(用两个栈实现队列)
    (转)c++一些知识点
    贪心算法
    动态规划——最长公共子串
    动态规划——主元素算法
  • 原文地址:https://www.cnblogs.com/hypnot/p/7978314.html
Copyright © 2011-2022 走看看