• 如何用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免费接口
    闲静少言,不求达内。乐于技,喜刨根,不求甚解;每有会意,其乐无穷。
  • 相关阅读:
    设计模式 之 单例模式
    leetcode 69 x 的平方根 牛顿迭代法
    leetcode 98 验证二叉搜索树
    leetcode 54 螺旋数组
    第一篇-python入门
    python-入门
    python
    线性判别分析LDA总结
    LDA
    线性判别分析(LDA)原理
  • 原文地址:https://www.cnblogs.com/hypnot/p/7978314.html
Copyright © 2020-2023  润新知