HttpUtils.php 2.4 KB
<?php


namespace App\Utils;


use App\Enums\Common\Code;
use App\Exceptions\BsideGlobalException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;


class HttpUtils
{
    /**
     * @notes: 异常处理
     * @param \Illuminate\Http\Client\Response $response
     * @return bool
     * @throws BsideGlobalException
     */
    public static function checkSuccess(Response $response)
    {
        // 确认状态码是否在 200 到 300 之间(包含 200)
        if ($response->successful()) {
            return true;
        }
        // 确认是否发生了 400 级别的错误(以 4 开头的状态码)  // 确认是否发生了 500 级别的错误(以 5 开头的状态码)
        if ($response->clientError() || $response->serverError()) {
            throw  new BsideGlobalException(Code::SERVER_ERROR);
        }
    }


    /**
     * get请求
     * @param $url
     * @param $data
     * @param $token
     * @return int
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function get($url, $data, $headers = [],$timeout=60)
    {
        LogUtils::info("HttpUtils-GET请求URL:" . $url);
        $response = Http::timeout($timeout)->withHeaders($headers)->get($url, $data);
        self::checkSuccess($response);
        return $response->getBody()->getContents();
    }

    public static function post($url, $data, $headers = [],$timeout=60)
    {
        LogUtils::info("HttpUtils-POST请求URL:" . $url);
        $response = Http::timeout($timeout)->withHeaders($headers)->post($url, $data);
        self::checkSuccess($response);
        return $response->getBody()->getContents();
    }

    /**
     * post raw
     * @param $url
     * @param $data
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function putRow($url, $data, $headers = [])
    {
        LogUtils::info("切换公司加密putRow入参:url:" . $url . '----data:', $data, $headers);
        if (is_array($data)) {
            $response = Http::withHeaders($headers)->put($url, $data);
        } else {
            $response = Http::withHeaders($headers)->send('PUT', $url, [
                'body' => $data
            ]);
        }

        self::checkSuccess($response);
        $body = $response->getBody()->getContents();

        LogUtils::info("切换公司加密putRow返回:", $body);
        return $body;


    }


}