Sample code for 30+ languages & platforms
Java

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 Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        Rest rest = new Rest();
        boolean bTls = true;
        boolean bAutoReconnect = true;
        try {
            rest.connect("example.com", 443, bTls, bAutoReconnect);

            rest.sendReqNoBody("GET", "/api/largefile");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int statusCode = rest.readResponseHeader();
        if (statusCode < 0) {
            System.out.println(rest.getLastErrorText());
            return;
        }

        // 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 (statusCode != 200) {
            StringBuilder sbError = new StringBuilder();
            try {
                rest.readRespSb(sbError);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            System.out.println("Request failed with status code " + statusCode);
            System.out.println(sbError.getAsString());
            return;
        }

        // 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.
        BinData bdBody = new BinData();
        int chunkResult = rest.readRespChunkBd(8192, bdBody);
        while (chunkResult > 0) {
            chunkResult = rest.readRespChunkBd(8192, bdBody);
        }

        if (chunkResult < 0) {
            System.out.println(rest.getLastErrorText());
            return;
        }

        System.out.println("Received " + bdBody.getNumBytes() + " bytes.");
    }
}