Home > Software engineering >  GuzzleHttp\Client cURL error 18: transfer closed
GuzzleHttp\Client cURL error 18: transfer closed

Time:04-08

I am using GuzzleHttp\Client Laravel 6 and I am getting this error when I am trying to get Data from API, it's working fine on postman

Here is My Code

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

getting this error

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

CodePudding user response:

I have resolved this issue , Maybe it will help someone

 $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();

CodePudding user response:

The error code 18

cURL error 18: transfer closed with outstanding read data remaining

as specified by curl errors,

CURLE_PARTIAL_FILE (18) A file transfer was shorter or larger than expected. This happens when the server first reports an expected transfer size, and then delivers data that does not match the previously given size.

since it is receiving a chunked encoding stream it knows when there is data left in a chunk to receive. When the connection is closed,curl tells that the last received chunk was incomplete. Thus you get this error code.

Why adding a Accept Encoding with gzip compression format works?

To solve the above problem we need a encode the data to preserve the packets to receive all of it, HTTP headers provides encoding and for the client i.e you to tell the server which encoding is supported, then the server responds accordingly and informs the client of its choice with the Content-Encoding response header.

'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();
  • Related