From 8052cd6f9fa1c2c6dc9dfdfbc7ef4cc3608544a3 Mon Sep 17 00:00:00 2001 From: twinh Date: Thu, 26 Oct 2023 20:46:40 +0800 Subject: [PATCH] =?UTF-8?q?feat(Http):=20=E6=94=AF=E6=8C=81=E4=BC=A0?= =?UTF-8?q?=E5=85=A5=20`json`=20=E6=9D=A5=E5=8F=91=E9=80=81=20json=20?= =?UTF-8?q?=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/Http.php | 12 ++++++++++++ tests/unit/HttpTest.php | 13 +++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/Http.php b/lib/Http.php index 8cab6e926..8b4b0cfce 100644 --- a/lib/Http.php +++ b/lib/Http.php @@ -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 * @@ -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); diff --git a/tests/unit/HttpTest.php b/tests/unit/HttpTest.php index 24b384bb4..aa24f819f 100644 --- a/tests/unit/HttpTest.php +++ b/tests/unit/HttpTest.php @@ -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')); @@ -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']); + } }