HttpUtils.php
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?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 = [])
{
LogUtils::info("HttpUtils-GET请求URL:" . $url);
$response = Http::withHeaders($headers)->get($url, $data);
self::checkSuccess($response);
return $response->getBody()->getContents();
}
public static function post($url, $data, $headers = [])
{
LogUtils::info("HttpUtils-POST请求URL:" . $url);
$response = Http::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;
}
}