使用场景:
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;
}
}