使用Guzzle请求的demo

<?php

use GuzzleHttp\Psr7;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/** 
 * curl类
 * @author SR.李
 */

class Curl
{
    // curl实例
    protected $client;
    protected $guzzleHeader = [
            // 'auth' => ['admin', 'admin'],
            'timeout'=> 10,
            'http_errors'=>false,
        ];


    public function __construct()
    {
        $this->header = $this->guzzleHeader;
        $this->client = new Client();
    }


    // 发送post请求
    public function curlApiPost($api, $header, $params = '')
    {
        $this->header['body'] = $params;
        $this->header = array_merge($header, $this->header);
        try {
            $response = $this->client->request('POST', $api, $this->header);
            if ($response->getStatusCode() != 200) \think\facade\Log::error($api.'状态码错误:'.$response->getStatusCode()."\n");
            $responseData = (string)$response->getBody();
            return $responseData;
        } catch (RequestException $e) {
            dump(Psr7\str($e->getResponse()));
            \think\facade\Log::error($api.'POST请求失败,响应结果'. Psr7\str($e->getResponse()) ."\n");
            // echo $api.'请求失败'."\n";
            return false;
        }
    }

    // 发送get请求
    public function curlApiGet(string $api, $header)
    {
        $this->header = array_merge($header, $this->header);
        try {
            $response = $this->client->request('GET', $api, $this->header);
            if ($response->getStatusCode() != 200) \think\facade\Log::error($api.'状态码错误:'.$response->getStatusCode()."\n");
            $responseData = (string)$response->getBody();
            return $responseData;
        } catch (RequestException $e) {
            \think\facade\Log::error($api.'GET请求失败,响应结果'. Psr7\str($e->getResponse()) ."\n");
            // echo $api.'请求失败'."\n";
            return false;
        }
    }
}