yii2.0 Curl 的使用

124 阅读1分钟
composer安装Curl

命令行切入到你的项目目录执行 composer require --prefer-dist linslin/yii2-curl "*" 等待安装即可 安装完之后curl的位置 项目根目录/vendor/linslin 有linslin就是安装成功了

yii2 Curl的使用办法

get:

use linslin\yii2\curl;
public function actionCurl($value =0)
{
    $url = 'http://yandex.ru/search/';
    $curl = new curl\Curl();
    //post http://example.com/, reset request before
    $response = $curl->reset()->setOption(
        CURLOPT_POSTFIELDS,
        http_build_query(array(
                'text' => $value
            )
        ))->post($url);
    return $curl->response;
    //get
    $authUrl = ‘http://www.baidu.com’;
    $curl = new Curl();
    $response = $curl->get($authUrl);
}

当访问https是可能会出现空白需要将ssl设置为false

$curl->setOption(CURLOPT_SSL_VERIFYPEER, false);

post:

// POST URL form-urlencoded 
// post 请求 , 数据格式为 form-urlencoded格式
$curl = new curl\Curl();
$response = $curl->setPostParams([
        'key' => 'value',
        'secondKey' => 'secondValue'
     ])
     ->post($authUrl);
// POST RAW JSON
// 发起post请求,数据为json格式
$curl = new curl\Curl();
$response = $curl->setRawPostData(
     json_encode([
        'key' => 'value',
        'secondKey' => 'secondValue'
     ]))
     ->post($authUrl);
// POST RAW XML
// 发起post请求,数据为xml格式
$curl = new curl\Curl();
$response = $curl->setRawPostData('<?xml version="1.0" encoding="UTF-8"?><someNode>Test</someNode>')
     ->post($authUrl);
// POST with special headers
// 发起post请求,并且设置header头部参数
$curl = new curl\Curl();
$response = $curl->setPostParams([
        'key' => 'value',
        'secondKey' => 'secondValue'
     ])
     ->setHeaders([
        'Custom-Header' => 'user-b'
     ])
     ->post($authUrl);
// POST JSON with body string & special headers
// 发起post请求,数据作为body以json串来传递,并且设置header头部参数
$curl = new curl\Curl();

$params = [
    'key' => 'value',
    'secondKey' => 'secondValue'
];

$response = $curl->setRequestBody(json_encode($params))
     ->setHeaders([
        'Content-Type' => 'application/json',
        'Content-Length' => strlen(json_encode($params))
     ])
     ->post($authUrl);
// Avanced POST request with curl options & error handling
post请求,设置参数
$curl = new curl\Curl();

$params = [
    'key' => 'value',
    'secondKey' => 'secondValue'
];
$response = $curl->setRequestBody(json_encode($params))
     ->setOption(CURLOPT_ENCODING, 'gzip')
     ->post($authUrl);
// List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
switch ($curl->responseCode) {

    case 'timeout':
        //timeout error logic here
        break;

    case 200:
        //success logic here
        break;

    case 404:
        //404 Error logic here
        break;
}
//list response headers
var_dump($curl->responseHeaders);
Yii2 Curl作为类调用
<?php
 namespace server\api;
 
 use yii;
 use yii\helpers\Json;
 use linslin\yii2\curl\Curl;
 /**
  * API基础类
 */
class BaseApi
{
    const API_POST = 'POST';//POST 请求
    const API_GET = 'GET';//GET 请求
    const API_HEAD = 'HEAD';// HEAD 请求
    const API_PUT = 'PUT';// PUT 请求
    const API_DELETE = 'DELETE'; // DELETE 请求


    /**
     * 调用脚本接口
     * @param $url 请求地址
     * @param $params 接口参数
     * @param $type 接口请求方式
     * @return array ['error' => 1, 'msg' => '错误信息', 'data' => '数据']
     */
    public function callApi($url, $params, $type = self::API_POST)
    {

        if (!$url) {
            return [
                'error' => 1,
                'message' => '脚本请求地址为空',
            ];
        }

        $ret = ['error' => 1];
        try {
            $curl = new Curl();
            // 请求方式
            $curl = $curl->setHeaders([
                'Content-Type' => 'application/json',
            ]);
            // 设置请求时间120秒
            $curl->setOption(CURLOPT_TIMEOUT, 120);

            switch ($type) {
                case self::API_GET:
                    if (!empty($params)) {
                        $url .= '?'.http_build_query($params);
                    }
                    $response = $curl->get($url);
                    break;

                case self::API_POST:
                    $response = $curl->setRawPostData(Json::encode($params))->post($url);
                    break;

                case self::API_PUT:
                    $response = $curl->setRawPostData(Json::encode($params))->put($url);
                    break;

                case self::API_DELETE:
                    $response = $curl->setRawPostData(Json::encode($params))->delete($url);
                    break;

                default:
                    $response = $curl->setRawPostData(Json::encode($params))->post($url);
                    break;
            }

            $result = $response ? Json::decode($response) : [];
            if (isset($result['result']) && $result['result'] == 'success') {
                $ret['error'] = 0;
                $ret['message'] = isset($result['msg']) ? $result['msg'] : 'successful';
                $ret['data'] = isset($result['data']) ? $result['data'] : [];
            } else {
                $ret['message'] = isset($result['msg']) ? $result['msg'] : '未知错误';
            }
        } catch (\Exception $e) {
            $ret['message'] = $e->getMessage().$this->_api_error_msg;
        }
        return $ret;
    }
}