封装代码

<?php

namespace App\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class Guzzle
{
    /**
     * GET请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function get($url, $options = [])
    {
        return self::sendRequest($url, 'GET', $options);
    }

    /** POST请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function post($url, $options = [], $is_json = 1)
    {
        if ($options['query']) {
            if ($is_json) {
                $options['json'] = $options['query'];
            } else{
                $options['form_params'] = $options['query'];
            }

            unset($options['query']);
        }
        return self::sendRequest($url, 'POST', $options);
    }

    /**
     * PUT请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function put($url, $options = [])
    {
        return self::sendRequest($url, 'PUT', $options);
    }

    /**
     * Delete请求
     * @param $url
     * @param array $options
     * @return mixed
     */
    public static function delete($url, $options = [])
    {
        return self::delete($url, $options);
    }

    public static function getOptions($params)
    {
        $baseOptions = [
            'connect_timeout' => 10,
            'timeout' => 10,
            'verify' => false,
            'debug' => false,
        ];
        $options = array_merge($baseOptions, $params);
        return $options;
    }
    /**
     * 发起HTTP请求
     * @param $url
     * @param string $method
     * @param array $options
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendRequest($url, string $method, array $options = [])
    {
        $options = self::getOptions($options);
        $client = new Client();
        try {
            $request = $client->request($method, $url, $options);
            $body = $request->getBody();
            $contents = $body->getContents();
            $response = json_decode($contents, true);
            return $response;

        } catch (ClientException $e) {
            // write log
            $response = [
                'code'=>$e->getCode(),
                'message'=> $e->getMessage(),
            ];
            echo json_encode($response);exit;
        }

    }
}

使用

<?php

namespace App\Http\Controllers;

use App\Services\Guzzle;

class TestController extends Controller
{

    public function send()
    {
        $baseUrl = 'https://xxxx.com';
        $apiName = '/api/generateimage';
        $url = $baseUrl.$apiName;
        $options = [
            'query' => [
                'id' => '1',
                'lang' => 'cn'
            ]
        ];
        $result = Guzzle::get($url, $options);
        dd($result);
    }
}

转自:https://blog.51cto.com/u_14097531/3859103

标签: none

添加新评论