Lazarus Pascal
Lazarus Pascal
Example: Http.DownloadAppend method
Demonstrates the DownloadAppend method.Chilkat Lazarus Pascal 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.Http,
Chilkat.StringBuilder,
Chilkat.FileAccess;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
targetPath: string;
http: THttp;
statusCode: Integer;
sb: TStringBuilder;
fac: TFileAccess;
begin
success := False;
targetPath := 'c:/temp/qa_output/download.txt';
http := THttp.Create;
http.KeepResponseBody := True;
// Assume the target file in the local filesystem does not yet exist.
success := http.DownloadAppend('https://chilkatsoft.com/testData/helloWorld.txt',targetPath);
statusCode := http.LastStatus;
if (statusCode = 0) then
begin
// Unable to either send the request or get the response.
WriteLn(http.LastErrorText);
Exit;
end;
// Should be 200.
WriteLn('Response status code: ' + statusCode);
// Examine the contents of the file.
sb := TStringBuilder.Create;
sb.LoadFile(targetPath,'utf-8');
WriteLn(sb.GetAsString());
// Output:
// Response status code: 200
// Hello World!
// Download another text file and append to the target file.
success := http.DownloadAppend('https://chilkatsoft.com/testData/this_is_a_test.txt',targetPath);
statusCode := http.LastStatus;
if (statusCode = 0) then
begin
// Unable to either send the request or get the response.
WriteLn(http.LastErrorText);
Exit;
end;
// Should be 200.
WriteLn('Response status code: ' + statusCode);
// Examine the contents of the file.
sb.LoadFile(targetPath,'utf-8');
WriteLn(sb.GetAsString());
// Output:
// Response status code: 200
// Hello World!This is a Test.
// Delete the local target file.
fac := TFileAccess.Create;
fac.FileDelete(targetPath);
// Try to download a file that does not exist:
success := http.DownloadAppend('https://chilkatsoft.com/testData/does_not_exist.txt',targetPath);
statusCode := http.LastStatus;
if (statusCode = 0) then
begin
// Unable to either send the request or get the response.
WriteLn(http.LastErrorText);
end
else
begin
// We got a response, and we already know it wasn't a 200 success response.
// It should be a 404 not found.
WriteLn('Response status code: ' + statusCode);
// Examine the response body.
WriteLn('Response body:');
WriteLn(http.LastResponseBody);
end;
http.Free;
sb.Free;
fac.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.