Sample code for 30+ languages & platforms
C

Read the REST Response Body into a StringBuilder

See more REST Examples

Demonstrates Rest.ReadRespSb, which reads the response body as text into a StringBuilder, replacing its previous contents.

Background. The staged request model separates sending from reading: a SendReq method transmits the request, ReadResponseHeader reads the status line and headers, and a ReadResp method reads the body. This gives fine control over large or streamed messages compared with the single-call full-request methods.

Chilkat C Downloads

C
#include <C_CkRest.h>
#include <C_CkStringBuilder.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkRest rest;
    BOOL bTls;
    BOOL bAutoReconnect;
    int statusCode;
    HCkStringBuilder sbResponse;
    const char *responseBody;

    success = FALSE;

    rest = CkRest_Create();
    bTls = TRUE;
    bAutoReconnect = TRUE;
    success = CkRest_Connect(rest,"example.com",443,bTls,bAutoReconnect);
    if (success == FALSE) {
        printf("%s\n",CkRest_lastErrorText(rest));
        CkRest_Dispose(rest);
        return;
    }

    success = CkRest_SendReqNoBody(rest,"GET","/api/items/123");
    if (success == FALSE) {
        printf("%s\n",CkRest_lastErrorText(rest));
        CkRest_Dispose(rest);
        return;
    }

    statusCode = CkRest_ReadResponseHeader(rest);
    if (statusCode < 0) {
        printf("%s\n",CkRest_lastErrorText(rest));
        CkRest_Dispose(rest);
        return;
    }

    //  Read the response body as text into a StringBuilder, replacing its previous contents.
    sbResponse = CkStringBuilder_Create();
    success = CkRest_ReadRespSb(rest,sbResponse);
    if (success == FALSE) {
        printf("%s\n",CkRest_lastErrorText(rest));
        CkRest_Dispose(rest);
        CkStringBuilder_Dispose(sbResponse);
        return;
    }

    responseBody = CkStringBuilder_getAsString(sbResponse);
    if (CkStringBuilder_getLastMethodSuccess(sbResponse) == FALSE) {
        printf("%s\n",CkStringBuilder_lastErrorText(sbResponse));
        CkRest_Dispose(rest);
        CkStringBuilder_Dispose(sbResponse);
        return;
    }

    printf("%s\n",responseBody);


    CkRest_Dispose(rest);
    CkStringBuilder_Dispose(sbResponse);

    }