/**
* 网络请求类
* Class HttpUtils
* @package App\Http\Controllers\Tools
*/
class RequestUtils
{
private static $self;
public static function getInstance()
{
if (!self::$self) {
self::$self = new self();
}
return self::$self;
}
/**
* @param $url
* @param array $data
* @return array|bool|float|int|object|string|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function get($url, $data = [])
{
if($data){
$url = strpos($url,"?")?$url."&".http_build_query($data):$url."?".http_build_query($data);
}
return $this->request($url, 'GET');
}
/**
* @param $url
* @param $data
* @param string $requestType
* @return array|bool|float|int|object|string|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function post($url, $data, $requestType = 'json')
{
return $this->request($url, 'POST', $data, $requestType);
}
/**
* @param $url
* @param $method
* @param array $contentData
* @param string $requestType
* @param int $timeOut
* @return array|mixed
*/
private function request($url, $method, $contentData = [], $requestType = 'json', $timeOut = 5)
{
try {
$client = new Client(['timeout' => $timeOut,'verify'=>false]);
$cost_time_start = microtime(true);
if ($method == 'POST') {
$info = $client->request($method, $url, [$requestType => $contentData]);
} else {
$info = $client->request($method, $url);
}
$cost_time_end = microtime(true);
$cost = $cost_time_end - $cost_time_start;
$response = $info->getBody()->getContents();
//记录全量请求结果
if (!$response) {
$result = ['code' => 1, 'data' => [], 'msg' => '网络异常'];
} else {
$result = json_decode($response, true);
}
$logData['response'] = $result;
#todo 记录日志
} catch (\Exception $e) {
$logData['exception'] = $e->getMessage();
//统一异常码
$result = ['code' => 1, 'data' => [], 'msg' => '网络请求一次'];
#todo 记录日志
}
return $result;
}
}
php网络请求工具类
最新推荐文章于 2024-04-07 09:53:00 发布