Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Read the REST Response Body into a Stream
See more REST Examples
Demonstrates Rest.ReadRespBodyStream, which reads the response body into a Stream. The optional flag sets the stream character set from the response Content-Type charset for textual responses.
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. 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 Pascal (Lazarus/Delphi) Downloads
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.Stream,
Chilkat.Rest;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
rest: TRest;
bTls: Boolean;
bAutoReconnect: Boolean;
statusCode: Integer;
respStream: TStream;
bAutoSetCharset: Boolean;
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.
success := rest.SendReqNoBody('GET','/api/images/1');
if (success = False) then
begin
WriteLn(rest.LastErrorText);
Exit;
end;
statusCode := rest.ReadResponseHeader();
if (statusCode < 0) then
begin
WriteLn(rest.LastErrorText);
Exit;
end;
// Read the response body into a Stream. Here the stream's sink is a local file, which is
// appropriate for large or binary responses.
respStream := TStream.Create;
respStream.SinkFile := 'qa_output/image.png';
// If the 2nd argument is True and the response is textual, the stream's character set is set from
// the response Content-Type charset. It has no effect for binary responses.
bAutoSetCharset := True;
success := rest.ReadRespBodyStream(respStream,bAutoSetCharset);
if (success = False) then
begin
WriteLn(rest.LastErrorText);
Exit;
end;
WriteLn('Response body written to the stream sink.');
rest.Free;
respStream.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.