Skip to content

Commit d251142

Browse files
committed
⚡ 优化请求参数
1 parent 775d9ac commit d251142

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

src/Traits/HttpRequest.php

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use GuzzleHttp\Client;
1515
use GuzzleHttp\Exception\GuzzleException;
1616
use GuzzleHttp\HandlerStack;
17+
use GuzzleHttp\Psr7\Utils;
1718

1819
trait HttpRequest
1920
{
@@ -29,6 +30,8 @@ trait HttpRequest
2930

3031
protected $param = [];
3132

33+
protected $fileParam = [];
34+
3235
protected $throw = false;
3336

3437
/**
@@ -68,18 +71,9 @@ public function setMethod(string $method)
6871
*
6972
* @return HttpRequest
7073
*/
71-
public function setParam(string $name, $value)
74+
public function setParam(string $name, $value, bool $is_file = false)
7275
{
73-
$this->param[$name] = $value;
74-
75-
return $this;
76-
}
77-
78-
public function setParams(array $param)
79-
{
80-
$params = array_merge($param, $this->param);
81-
82-
$this->param = $params;
76+
$this->param[] = ['name' => $name, 'value' => $value, 'is_file' => $is_file];
8377

8478
return $this;
8579
}
@@ -117,15 +111,29 @@ public function throw()
117111
public function request(): Result
118112
{
119113
$client = $this->createHttpClient();
120-
if(!$this->api){
121-
throw new ALAPIException('api cannot be empty');
114+
if (!$this->api) {
115+
throw new ALAPIException('API 不能为空');
122116
}
123117

118+
$method = $this->method;
124119
$options = [];
125-
if ('get' == $this->method) {
126-
$options['query'] = $this->param;
120+
if ('get' === $method) {
121+
$query = [];
122+
foreach ($this->param as $key => $item) {
123+
$query[$item['name']] = $item['value'];
124+
}
125+
$options['query'] = $query;
127126
} else {
128-
$options['form_params'] = $this->param;
127+
$multipart = [];
128+
foreach ($this->param as $key => $item) {
129+
$multipart[$key]['name'] = $item['name'];
130+
if ($item['is_file']) {
131+
$multipart[$key]['contents'] = Utils::tryFopen($item['value'], 'r');
132+
} else {
133+
$multipart[$key]['contents'] = $item['value'];
134+
}
135+
}
136+
$options['multipart'] = $multipart;
129137
}
130138

131139
try {

0 commit comments

Comments
 (0)