From 49adca198f1fdbecf26a7638eaa39fc516f8822b Mon Sep 17 00:00:00 2001 From: twinh Date: Tue, 24 Oct 2023 23:44:57 +0800 Subject: [PATCH] =?UTF-8?q?feat(Http):=20=E5=A6=82=E6=9E=9C=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=86=85=E5=AE=B9=E6=98=AF=20`application/json`?= =?UTF-8?q?=EF=BC=8C=E5=88=99=E8=87=AA=E5=8A=A8=E8=A7=A3=E6=9E=90=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=86=85=E5=AE=B9=E4=B8=BA=20JSON=20=E6=95=B0?= =?UTF-8?q?=E7=BB=84=EF=BC=8C=E8=80=8C=E4=B8=8D=E6=98=AF=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E7=BA=AF=E6=96=87=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BREAKING CHANGE: `Http` 服务如果返回内容是 `application/json`,则自动解析返回内容为 JSON 数组,而不是返回纯文本 --- lib/Http.php | 13 +++++++++---- tests/unit/HttpTest.php | 12 ++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/lib/Http.php b/lib/Http.php index 0cfe251fa..b1de24504 100644 --- a/lib/Http.php +++ b/lib/Http.php @@ -121,9 +121,9 @@ class Http extends Base implements \ArrayAccess, \Countable, \IteratorAggregate * The data type could by `json`, `jsonObject`, `xml`, `query`(URL query string), * `serialize` and `text` * - * @var string + * @var string|null */ - protected $dataType = 'text'; + protected $dataType; /** * The custom HTTP referer string @@ -999,10 +999,15 @@ protected function triggerError($status, \ErrorException $exception) */ protected function parseResponse($data, &$exception) { - switch ($this->dataType) { + $dataType = $this->dataType; + if (!$dataType && 'application/json' === $this->getResponseHeader('CONTENT-TYPE')) { + $dataType = 'json'; + } + + switch ($dataType) { case 'json': case 'jsonObject': - $result = json_decode($data, 'json' === $this->dataType); + $result = json_decode($data, 'json' === $dataType); if (null === $result && \JSON_ERROR_NONE != json_last_error()) { $exception = new \ErrorException('JSON parsing error, the data is ' . $data, json_last_error()); } diff --git a/tests/unit/HttpTest.php b/tests/unit/HttpTest.php index 69b7f3b92..046e82b32 100644 --- a/tests/unit/HttpTest.php +++ b/tests/unit/HttpTest.php @@ -1095,4 +1095,16 @@ public function providerForParams(): array ], ]; } + + public function testDetectJson() + { + $http = $this->http->get([ + 'url' => 'https://httpbin.org/get', + ]); + $this->assertSame('application/json', $http->getResponseHeader('CONTENT-TYPE')); + + $response = $http->getResponse(); + $this->assertIsArray($response); + $this->assertSame('https://httpbin.org/get', $response['url']); + } }