hyperf Guzzle Client get post请求封装

简单封装了hyperf get post请求,记录一下。 需要使用的小伙伴添加一个Exception类则可,代码已提供。

使用方式:

//get请求
$curl = new Curl();
$url    = "https://www.uikid.com/xxxx"
$params = ['name' => 'Seal', 'age' => 105];
$responseJson = $curl->get($url, $params);
$responseData = Json::decode($responseJson);

//post请求
$curl = new Curl();
$url    = "https://www.uikid.com/xxxx"
$params = ['name' => 'Seal', 'age' => 105];
$header=['Content-Type' => 'application/json;charset=utf-8',]; //默认可不传
$responseJson = $curl->post($url, $params);
$responseData = Json::decode($responseJson);

Curl类:

<?php
declare(strict_types=1);

namespace App\Extend\CommonSdk\Curl;


use App\Extend\CommonSdk\Exception\BaseException;
use App\Extend\CommonSdk\Tool\Json;
use GuzzleHttp\Client;
use Hyperf\Guzzle\HandlerStackFactory;

class Curl
{
    /**
     * @var Client
     */
    private $client;


    /**
     * Curl constructor.
     */
    public function __construct()
    {
        $factory = new HandlerStackFactory();
        $stack   = $factory->create();

        $this->client = make(Client::class, [
            'config' => [
                'handler' => $stack,
            ],
        ]);
    }

    /**
     * 检查返回http状态码
     *
     * @param \Psr\Http\Message\ResponseInterface $response
     */
    private function adjustResponse($response)
    {
        if (200 !== $response->getStatusCode()) {
            throw new BaseException("请求失败,详情:" . $response->getReasonPhrase());
        }
    }

    /**
     * 发送get请求
     *
     * @param string $url
     * @param array  $params
     *
     * @return string
     */
    public function get(string $url, array $params)
    {
        $client = $this->client;

        $response = $client->get($url, ['query' => $params]);

        $this->adjustResponse($response);

        return $response->getBody()->getContents();
    }

    /**
     * 发送Post请求
     *
     * @param string $url
     * @param array  $body
     * @param array  $headers
     *
     * @return string
     */
    public function post(
        string $url,
        array $body,
        array $headers = ['Content-Type' => 'application/json;charset=utf-8',]
    ) {
        $response = $this->client->post($url, [
            'body'    => Json::encode($body),
            'headers' => $headers,
        ]);

        $this->adjustResponse($response);

        return $response->getBody()->getContents();
    }

}

Exception类:

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Extend\CommonSdk\Exception;

use Hyperf\Server\Exception\ServerException;
use Throwable;

class BaseException extends ServerException
{
    public function __construct(string $message = null, int $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}