关于guzzleHttp的基础操作

    Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。Guzzle有许多特点,这里引用官网上的介绍

  • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
  • 发送同步或异步的请求均使用相同的接口。
  • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
  • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
  • 中间件系统允许你创建构成客户端行为。

    首先安装composer,Composer是PHP的依赖管理工具,允许你在项目中声明依赖关系,并安装这些依赖。

curl -sS https://getcomposer.org/installer | php


接着使用使用composer.phar客户端将Guzzle作为依赖添加到项目:

php composer.phar require guzzlehttp/guzzle:~6.0

此时添加Guzzle依赖已经完成,接着我们封装一些常用的方法

<?php
/**
 * Created by PhpStorm.
 * User: noodles
 */
namespace App\lib;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise;

class Guzzle {

    private static $guzzle = [];

    /**
     * 释放资源
     */
    public static function closeAllConns(){
        if( count(self::$guzzle) === 0 ){
            return true;
        }
        foreach (self::$guzzle as $conn){
            $conn = null;
        }
    }

    /**
     * 实例化guzzle(单例)
     * @param $base_uri  uri
     * @return bool
     */
    private static function init($base_uri) {

        if( !isset($guzzle[$base_uri]) ){

            if( !isset(self::$guzzle[$base_uri]) ){
                if(empty($base_uri)){
                    return false;
                }
                self::$guzzle[$base_uri] = new Client([
                    // Base URI is used with relative requests
                    'base_uri' => $base_uri,
                    // You can set any number of default request options.
                    'timeout'  => 10.0,
                    // https请求
                    'verify' => false
                ]);
            }
        }
        return true;
    }

    /**
     * 获取guzzle实例
     * @param $base_uri   uri
     * @return bool|mixed
     */
    public static function getGuzzle($base_uri) {
        $ret = Guzzle::init($base_uri);
        if($ret == false){
            return false;
        }
        return self::$guzzle[$base_uri];
    }

    /**
     * post请求
     * @param string $base_uri   设置uri
     * @param string $api   请求api
     * @param array $post_data   请求数据
     * @param array $headers  请求头
     * @param string $type   请求类型 json
     * @param string $cookie  请求cookies
     * @return mixed
     * @throws \Exception
     */
    public static function guzzle_post($base_uri, $api, $post_data = [], $headers = [], $type = 'json', $cookie = '') {
        $guzzle_ins = Guzzle::getGuzzle($base_uri);
        try{
            if($type === 'json'){
                $data = [
                    'headers' => $headers,
                    'json' => $post_data,
                    'cookies' => $cookie,
                ];
            }else{
                $data = [
                    'headers' => $headers,
                    'body' => $post_data,
                    'cookies' => $cookie,
                ];
            }
            $response = $guzzle_ins->post($api, $data);
            $response_code = $response->getStatusCode();
            $ret = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
            return $ret;
        }catch (RequestException $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**    
     * post请求(异步)
     * @param string $base_uri   设置uri
     * @param string $api  请求api
     * @param array $post_data  请求数据
     * @param array $headers  请求头
     * @param string $type  请求类型 json
     * @param string $cookie   请求cookies
     * @return array|mixed
     * @throws \Exception
     */
    public static function guzzle_postAsync($base_uri, $api, $post_data = [], $headers = [], $type = 'json', $cookie = '') {
        $guzzle_ins = Guzzle::getGuzzle($base_uri);
        $info = [];
        try{
            if($type === 'json'){
                $data = [
                    'headers' => $headers,
                    'json' => $post_data,
                    'cookies' => $cookie,
                ];
            }else{
                $data = [
                    'headers' => $headers,
                    'body' => $post_data,
                    'cookies' => $cookie,
                ];
            }
            $promises = [$guzzle_ins->postAsync($api, $data)];
            $ret = Promise\unwrap($promises);
            foreach ($ret as $k => $v){
                $info =  \GuzzleHttp\json_decode($v->getBody()->getContents(), true);   //获取server端返回值
            }
            return $info;
        }catch (RequestException $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * get请求
     * @param string $base_uri   设置uri
     * @param string $api 请求api
     * @param array $headers 请求头
     * @return mixed
     * @throws \Exception
     */
    public static function guzzle_get($base_uri, $api, $headers = []) {
        $guzzle_ins = Guzzle::getGuzzle($base_uri);
        try{
            $data = [
                'headers' => $headers,
            ];
            $response = $guzzle_ins->get($api, $data);
            $response_code = $response->getStatusCode();
            $ret = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
            return $ret;
        }catch (RequestException $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * get请求(异步)
     * @param string $base_uri   设置uri
     * @param string $api 请求api
     * @param array $headers 请求头
     * @return mixed
     * @throws \Exception
     */
    public static function guzzle_getAsync($base_uri, $api, $headers = []){
        $guzzle_ins = Guzzle::getGuzzle($base_uri);
        $info = [];
        try{
            $data = [
                'headers' => $headers,
            ];
            $promises = [$guzzle_ins->getAsync($api, $data)];
            $ret = Promise\unwrap($promises);

            foreach ($ret as $k => $v){
                $info =  \GuzzleHttp\json_decode($v->getBody()->getContents(), true);   //获取server端返回值
            }
            return $info;
        }catch (RequestException $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * get请求(并行异步)
     * @param string $base_uri   设置uri
     * @param string $api 请求api
     * @param array $headers 请求头
     * @return mixed
     * @throws \Exception
     */
    public static function guzzle_getAsyncAll($base_uri, Array $api){
        $guzzle_ins = Guzzle::getGuzzle($base_uri);
        try{
            $promises = [];
            $info = [];
            if(!empty($api)){
                foreach ($api as $value){
                    array_push($promises, $guzzle_ins->getAsync($value));
                }
            }
            $ret = Promise\unwrap($promises);   //客户端发起请求并等待所有的请求结束再返回结果
            foreach ($ret as $k => $v){
                $info[] =  \GuzzleHttp\json_decode($v->getBody()->getContents(), true);   //获取server端返回值
            }
            return $info;
        }catch (RequestException $e){
            throw new \Exception($e->getMessage());
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值