laravel8使用GuzzleHttp\Client类发起各类请求示例

使用场景:
laravel8 中的GuzzleHttp\Client类,发起get/post请求,以各种方式参数,获取数据
示例代码:

namespace App\Services;

use GuzzleHttp\Client as HttpClient;
use Illuminate\Support\Facades\Log;

class httpService
{
    private $sRequestUrl;//图片提取文字
    private $oHttp;

    public function __construct()
    {
        $this->sRequestUrl = 'http://xxxx.xxx.xx';
        $this->oHttp = new HttpClient();
    }


    /**
     * post请求 正常传参
     * @return false|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function requestPostArrayData()
    {
        $aRequestData = [
            'form_params' => [
                'name' => 'lily',
                'sex' => 'girl',
                'age' => 12
            ],
            'timeout' => 300
        ];
        $sResult = $this->oHttp->post($this->sRequestUrl, $aRequestData)->getBody()->getContents();
        if(!$sResult) {
            Log::info('error:' . $sResult);
            return false;
        }
        $aResult = json_decode($sResult, true);
        return $aResult;
    }

    /**
     * 下载远程大文件到本地服务器并保存
     * @param $iMsgId
     * @param $sFilePath
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function downloadBigFile($iMsgId, $sFilePath)
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        // 使用 Guzzle HTTP 客户端下载音频文件 使用流式传输功能来处理大文件,从而避免内存不足的问题
        $aRequesData = ['stream' => true, 'timeout' => 300];
        $oResponse = $this->oHttp->request('GET', $sFilePath, $aRequesData);
        //从响应流中读取音频内容
        $oSteam = $oResponse->getBody();

        //获取文件后缀名
        $sExt = pathinfo($sFilePath, PATHINFO_EXTENSION);
        // 重命名音频文件名
        $sFileName = 'msgfile_' . $iMsgId . '.' . $sExt;
        //自定义文件夹名 并创建本地文件夹、文件
        $sDirPath = public_path('uploadfile/msg');
        mkdirs($sDirPath);
        $sLocalPath = $sDirPath . '/' . $sFileName;
        //若已存在,先删除原文件再新建
        if(file_exists($sLocalPath)) {
            @unlink($sLocalPath);
        }
        //打开本地文件,写入音频文件内容
        $sLocalFile = fopen($sLocalPath, 'w+');
        stream_copy_to_stream($oSteam->detach(), $sLocalFile);
        //关闭本地文件并返回成功消息
        fclose($sLocalFile);

        $sPath = '/uploadfile/msg/' . $sFileName;

        return $sPath;
    }

    /**
     * 上传图片 post请求 form-data方式传参 (包含远程图片文件)
     * @param $sImgFilePath
     * @return false|mixed|string[]
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function requestPosFormData($sImgFilePath)
    {
        //image content_type
        $sImgExt = pathinfo($sImgFilePath, PATHINFO_EXTENSION);
        $sImgType = $sImgExt == 'jpg' ? 'image/jpeg' : ($sImgExt == 'png' ? 'image/png' : '');
        if(!$sImgType) return ['error' => 'image is invalid'];
        //form-data 方式传参
        $aData = [
            'multipart' => [
                [
                    'name' => 'mark' ,
                    'contents' => 'test'
                ],
                //传递图片-相关参数
                [
                    'name' => 'img',
                    'contents' => file_get_contents($sImgFilePath),//可读取远程文件,文件过大会超限制,适用于小文件
                    'filename'=> basename($sImgFilePath),
                    'headers' => [
                        'Content-Type' => $sImgType
                    ]
                ]
            ],
            //设置超时时间
            'timeout' => 300
        ];
        $sResult = $this->oHttp->post($this->sRequestUrl, $aData)->getBody()->getContents();
        if(!$sResult) {
            Log::info('img error:' . $sResult);
            return false;
        }
        $aResult = json_decode($sResult, true);
        return $aResult;
    }

    /**
     * 发起 post请求 json格式传参
     * @param $aData
     * @return false|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function requestPostJsonData($aData)
    {
        //json格式传参
        $aRequestData = [
            'json' => $aData,
            'headers' => [ 'Content-Type' => 'application/json']
        ];
        $sResult = $this->oHttp->post($this->sRequestUrl, $aRequestData)->getBody()->getContents();
        $sResult = json_decode($sResult, true);
        if(!$sResult) {
            Log::info('img error:' . $sResult);
            return false;
        }

        $aResult = json_decode($sResult, true);
        return $aResult;
    }

    /**
     * post请求  form-data方式传参 传递大文件(本地)
     * @param $sFilePath
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function requestPostFormDataFile($sFilePath)
    {
        //form-data 方式传参
        $aData = [
            'multipart' => [
                [
                    'name' => 'domain' ,
                    'contents' => 'emaibo'
                ],
                [
                    'name' => 'role' ,
                    'contents' => 'true'
                ],
                [
                    'name' => 'file',
                    'contents' => fopen($sFilePath, 'r'),//fopen仅能读取本地服务器中的文件
                    'filename'=> basename($sFilePath)
                ]
            ],
            'timeout' => 300
        ];
        $sToken = $this->oHttp->post($this->sAudio, $aData)->getBody()->getContents();
        return $sToken;
    }

    /**
     * php curl post请求 form-data数据
     * 可传递文件或图片 示例
     * $aData = [
     *  'file' => new \CURLFile($sFilePath), //传递文件(包含音频等)php5.6+
     *  'img' => new \CURLFile($sImgFilePath, $sImgType) //传递图片文件 php5.6+
     *  'role' => 'true'
     * ];
     * @param $sUrl
     * @param $sFilePath
     * @param $aData
     * @param $iTimeout
     * @return bool|string
     */
    protected function httpPostForm($sUrl, $sFilePath, $aData, $iTimeout = 300)
    {
        if ( ! file_exists($sFilePath)) {
            Log::channel('message-voice')->info('语音接口File not found: ' . $sFilePath);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $aData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $iTimeout);
        $sResult = curl_exec($ch);
        if (curl_errno($ch)) {
            Log::channel('message-voice')->info('语音接口cURL error: ' . curl_error($ch));
        }

        curl_close($ch);

        return $sResult;
    }
}

	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 GuzzleHttp 发送 multipart/form-data POST 请求,可以按照以下步骤进行: 1. 首先,需要使用 Composer 安装 GuzzleHttp: ``` composer require guzzlehttp/guzzle ``` 2. 在需要使用 GuzzleHttp 的文件中引入 GuzzleHttp: ```php use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; ``` 3. 构造 GuzzleHttp 客户端: ```php $client = new Client(); ``` 4. 构造发送的数据: ```php $data = [ [ 'name' => 'field1', 'contents' => 'value1' ], [ 'name' => 'field2', 'contents' => 'value2' ], [ 'name' => 'file', 'contents' => fopen('/path/to/file', 'r'), 'filename' => 'filename.jpg' ] ]; ``` 其中,第一个和第二个元素是普通的键值对,第三个元素是上传的文件,使用 `fopen()` 函数打开文件并传递给 `'contents'` 参数。 5. 发送请求: ```php $response = $client->request('POST', 'https://example.com/upload', [ 'multipart' => $data ]); ``` 其中,`'multipart'` 参数指定了发送的数据格式为 multipart/form-data。 完整代码示例: ```php use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; $client = new Client(); $data = [ [ 'name' => 'field1', 'contents' => 'value1' ], [ 'name' => 'field2', 'contents' => 'value2' ], [ 'name' => 'file', 'contents' => fopen('/path/to/file', 'r'), 'filename' => 'filename.jpg' ] ]; $response = $client->request('POST', 'https://example.com/upload', [ 'multipart' => $data ]); ``` 注意,这里的 `'https://example.com/upload'` 是示例网址,请替换成你需要发送的实际网址。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值