Skip to content

Commit

Permalink
feat(Http): 支持传入 json 来发送 json 数据
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Nov 2, 2023
1 parent 94add7a commit 8052cd6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ class Http extends Base implements \ArrayAccess, \Countable, \IteratorAggregate
*/
protected $data = [];

/**
* The json data to send to the server
*
* @var array
*/
protected $json = [];

/**
* The files send to the server
*
Expand Down Expand Up @@ -822,6 +829,11 @@ protected function prepareCurlOptions()
}
}

if ($this->json) {
$opts[\CURLOPT_POSTFIELDS] = json_encode($this->json, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE);
$this->headers['Content-Type'] = 'application/json';
}

if ($this->files) {
$postFields = isset($opts[\CURLOPT_POSTFIELDS]) ? $opts[\CURLOPT_POSTFIELDS] : '';
$opts[\CURLOPT_POSTFIELDS] = $this->addFileField($postFields, $this->files);
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/HttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,7 @@ public function testDetectJson()
{
$http = $this->http->get([
'url' => 'https://httpbin.org/get',
'ip' => false,
]);
$this->assertSame('application/json', $http->getResponseHeader('CONTENT-TYPE'));

Expand All @@ -1065,4 +1066,16 @@ public function testNewInstance()
{
$this->assertNotSame(Http::instance(), Http::instance());
}

public function testJson()
{
$http = Http::post([
'url' => 'https://httpbin.org/post',
'json' => [
'a' => 'b',
],
]);
$this->assertSame('application/json', $http['headers']['Content-Type']);
$this->assertSame('b', $http['json']['a']);
}
}

0 comments on commit 8052cd6

Please sign in to comment.