Sample code for 30+ languages & platforms
AutoIt

Read the REST Response Body in Chunks

See more REST Examples

Demonstrates Rest.ReadRespChunkBd, which reads the response body one chunk at a time, appending each chunk to a BinData. A return value of 0 signals the body is complete, while -1 indicates a read failure.

Background. Chunked reading lets an application process a large response incrementally rather than buffering the entire body at once. It is used after ReadResponseHeader within the staged request model.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

$oRest = ObjCreate("Chilkat.Rest")
Local $bTls = True
Local $bAutoReconnect = True
$bSuccess = $oRest.Connect("example.com",443,$bTls,$bAutoReconnect)
If ($bSuccess = False) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.SendReqNoBody("GET","/api/largefile")
If ($bSuccess = False) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

Local $iStatusCode = $oRest.ReadResponseHeader()
If ($iStatusCode < 0) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

;  Check for the expected success status code.  If the response is not 200, the body is likely
;  error text formatted as JSON, XML, or HTML rather than the expected content.  In that case read
;  the body as text, report it, and return.
If ($iStatusCode <> 200) Then
    $oSbError = ObjCreate("Chilkat.StringBuilder")
    $bSuccess = $oRest.ReadRespSb($oSbError)
    If ($bSuccess = False) Then
        ConsoleWrite($oRest.LastErrorText & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Request failed with status code " & $iStatusCode & @CRLF)
    ConsoleWrite($oSbError.GetAsString() & @CRLF)
    Exit
EndIf

;  The status code is 200.  Read the response body in chunks, appending each chunk to the BinData.
;  Each call waits until at least the requested number of bytes is available, unless the response
;  ends first.  A return value of 0 means the final bytes were returned and the body is complete;
;  -1 indicates a read failure.
$oBdBody = ObjCreate("Chilkat.BinData")
Local $iChunkResult = $oRest.ReadRespChunkBd(8192,$oBdBody)
While $iChunkResult > 0
    $iChunkResult = $oRest.ReadRespChunkBd(8192,$oBdBody)
Wend
If ($iChunkResult < 0) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

ConsoleWrite("Received " & $oBdBody.NumBytes & " bytes." & @CRLF)