GuzzleHttp\Client cURL错误18:传输已关闭



我正在使用GuzzleHttpClientLaravel 6,当我试图从API获取数据时,我收到了这个错误,它在邮递员上运行良好

这是我的代码

try {
$client = new Client();
$result = $client->request("POST", $this->url,
[
'headers' => [
'Authorization' => 'Bearer ' . $this->ApiToken
],
]);
$content = $result->getBody()->getContents();
return [
'bool' => true,
'message' => 'Success',
'result' => $content,
];
}  catch (Exception  $exception) {
return [
'bool' => false,
'message' => $exception->getMessage()
];
}

得到这个错误

cURL error 18: transfer closed with outstanding read data remaining (see https://curl.haxx.se/libcurl/c/libcurl-errors.html

我已经解决了这个问题,也许它会帮助

$client = new Client();
$result = $client->request("POST", $this->url,
[
'headers' => [
'Authorization' => 'Bearer ' . $this->ApiToken,
'Accept-Encoding' => 'gzip, deflate', //new line added
],
]);
$content = $result->getBody()->getContents();

错误代码18

cURL错误18:传输已关闭,剩余未完成的读取数据为

由卷曲错误、指定

CURLE_PARTIAL_FILE(18(文件传输比预期的要短或要大。当服务器首先报告预期的传输大小,然后传递数据与之前给定的大小不匹配。

因为它正在接收分块编码流,所以它知道何时块中还有数据要接收。当连接关闭时,curl告诉最后一个接收到的chunk是不完整的。这样你就得到了这个错误代码。

为什么使用gzip压缩格式添加Accept Encoding有效

为了解决上述问题,我们需要对数据进行编码,以保留接收所有数据的数据包,HTTP标头提供编码,并为客户端(即,您告诉服务器支持哪种编码(,然后服务器相应地做出响应,并用内容编码响应标头通知客户端其选择。

'Accept-Encoding' => 'gzip,                      deflate                   br'
encoding technique       compression format(zlib)  providing one more compression format as alternate to the server
$result = $client->request("POST", $this->url,
[
'headers' => [
'Authorization' => 'Bearer ' . $this->ApiToken,
'Accept-Encoding' => 'gzip, deflate, br', //add encoding technique
],
]);
$content = $result->getBody()->getContents();

最新更新