Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Send a REST Request with a Binary Body

See more REST Examples

Demonstrates Rest.FullRequestBd, which sends a complete request whose binary body is read from a BinData and stores the text response body in a StringBuilder.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. FullRequestBd is used when the request payload is binary, such as an image or other file, while the response is textual (for example a JSON acknowledgement).

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.BinData,
  Chilkat.Rest,
  Chilkat.StringBuilder;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  rest: TRest;
  bTls: Boolean;
  bAutoReconnect: Boolean;
  bdRequest: TBinData;
  bLoaded: Boolean;
  sbResponse: TStringBuilder;
  responseText: string;

begin
  success := False;

  rest := TRest.Create;
  bTls := True;
  bAutoReconnect := True;
  success := rest.Connect('example.com',443,bTls,bAutoReconnect);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;

  //  The file paths are relative to the application's current working directory.  Absolute paths
  //  may also be used.  Supply the paths appropriate to your own environment.

  //  FullRequestBd sends a request whose binary body is read from a BinData and stores the text
  //  response body in a StringBuilder.
  bdRequest := TBinData.Create;
  bLoaded := bdRequest.LoadFile('qa_data/image.png');
  if (bLoaded <> True) then
    begin
      WriteLn('Failed to load the request body file.');
      Exit;
    end;

  rest.AddHeader('Content-Type','image/png');

  sbResponse := TStringBuilder.Create;
  success := rest.FullRequestBd('PUT','/api/images/1',bdRequest,sbResponse);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;

  responseText := sbResponse.GetAsString();
  if (sbResponse.LastMethodSuccess = False) then
    begin
      WriteLn(sbResponse.LastErrorText);
      Exit;
    end;
  WriteLn(responseText);


  rest.Free;
  bdRequest.Free;
  sbResponse.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.