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']); + } }