OneDrive: Download Binary Data into Memory
See more OneDrive Examples
GET /content can return HTTP 200 with file bytes directly, or HTTP 302 with a service URL. Handle both instead of requiring a redirect. Check transport completion and HTTP status, and compare Content-Length to the received byte count when supplied. Requests specify identity encoding; unexpected content encodings are rejected. A successful zero-byte file is valid. A 401 can mean an expired token, wrong audience, or expired preauthenticated URL; a 403 can indicate missing grants or policy restrictions.
After validating the final response, GetBodyBd copies its raw bytes into BinData. This supports both direct Graph content and returned service URLs. The entire response is held in memory; use the disk example for large files. Content is not printed.
Returned service URLs are used unchanged with automatic redirects disabled. Graph URLs on graph.microsoft.com:443 use the Graph token. A separate SharePoint token is sent only to the exact configured host on port 443. Legacy URLs carrying tempauth are used without a bearer token, even when a SharePoint cache exists. Other content hosts receive no bearer token. HTTPS and absence of embedded login credentials are checked. Unexpected redirects stop rather than forwarding credentials.
For authenticated SharePoint transfers, prepare private qa_data/tokens/oneDrive-sharepoint.json containing host (a bare trusted hostname, such as tenant.sharepoint.com) and access_token issued for that SharePoint resource. Keep it separate from the Graph token cache. The app must obtain consent and acquire/refresh the SharePoint token separately; these transfer examples do not do that automatically. Use the appropriate tenant/resource/account and current permissions. On 401, renew the appropriate token or obtain a fresh legacy URL; do not blindly retry a write or forward the Graph token to SharePoint.
See the OneDrive guide: transfer authentication and Microsoft's current returned-URL behavior.
Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.
Permission: Files.Read.
Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.
For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.
Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.
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.Url,
Chilkat.FileAccess,
Chilkat.HttpResponse,
Chilkat.StringBuilder,
Chilkat.JsonObject,
Chilkat.Http,
Chilkat.BinData;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
token: TJsonObject;
http: THttp;
resp: THttpResponse;
result: TJsonObject;
driveId: string;
itemId: string;
endpoint: TStringBuilder;
downloadUrl: string;
serviceUrl: TUrl;
downloadHttp: THttp;
serviceHost: TStringBuilder;
serviceQuery: TStringBuilder;
authMatch: TJsonObject;
authMatched: Integer;
tokenFiles: TFileAccess;
sharepointToken: TJsonObject;
fileData: TBinData;
actualSize: TStringBuilder;
contentEncoding: TStringBuilder;
declaredLength: TStringBuilder;
lengthMatch: TJsonObject;
lengthMatched: Integer;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
token := TJsonObject.Create;
token.Strict := True;
success := token.LoadFile('qa_data/tokens/oneDrive.json');
if (success <> True) then
begin
WriteLn('Could not load the private OneDrive token cache.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
http := THttp.Create;
http.AuthToken := token.StringOf('access_token');
http.RequireSslCertVerify := True;
http.FollowRedirects := False;
http.ConnectTimeout := 20;
http.ReadTimeout := 120;
http.SetRequestHeader('Accept','application/json');
resp := THttpResponse.Create;
result := TJsonObject.Create;
result.Strict := True;
driveId := 'YOUR_DRIVE_ID';
itemId := 'YOUR_ITEM_ID';
endpoint := TStringBuilder.Create;
endpoint.Append('https://graph.microsoft.com/v1.0/drives/');
endpoint.Append(http.UrlEncode(driveId));
endpoint.Append('/items/');
endpoint.Append(http.UrlEncode(itemId));
endpoint.Append('/content');
http.SetRequestHeader('Accept','*/*');
http.SetRequestHeader('Accept-Encoding','identity');
success := http.HttpNoBody('GET',endpoint.GetAsString(),resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200) and (resp.StatusCode <> 302)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
if (resp.StatusCode = 302) then
begin
downloadUrl := resp.GetHeaderField('Location');
serviceUrl := TUrl.Create;
success := serviceUrl.ParseUrl(downloadUrl);
if (success <> True) then
begin
WriteLn('Invalid returned service URL.');
Exit;
end;
if ((serviceUrl.Ssl <> True) or (serviceUrl.Host = '') or (serviceUrl.Login <> '') or (serviceUrl.Password <> '')) then
begin
WriteLn('Expected an HTTPS service URL without embedded login credentials.');
Exit;
end;
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
downloadHttp := THttp.Create;
downloadHttp.RequireSslCertVerify := True;
downloadHttp.FollowRedirects := False;
downloadHttp.ConnectTimeout := 20;
downloadHttp.ReadTimeout := 120;
serviceHost := TStringBuilder.Create;
serviceHost.Append(serviceUrl.Host);
serviceQuery := TStringBuilder.Create;
serviceQuery.Append(serviceUrl.Query);
authMatch := TJsonObject.Create;
authMatched := serviceQuery.RegexMatch('(?i)(?:^|[?&])tempauth=[^&]+',authMatch,100);
if (authMatched < 0) then
begin
WriteLn('Could not inspect the service URL query.');
Exit;
end;
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if (authMatched = 0) then
begin
if ((serviceHost.ContentsEqual('graph.microsoft.com',False) = True) and (serviceUrl.Port = 443)) then
begin
downloadHttp.AuthToken := token.StringOf('access_token');
end
else
begin
tokenFiles := TFileAccess.Create;
if (tokenFiles.FileExists('qa_data/tokens/oneDrive-sharepoint.json') = True) then
begin
sharepointToken := TJsonObject.Create;
sharepointToken.Strict := True;
success := sharepointToken.LoadFile('qa_data/tokens/oneDrive-sharepoint.json');
if (success <> True) then
begin
WriteLn('Could not read the private SharePoint token cache.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('host') <> 1) or (sharepointToken.StringOfEquals('host','',True) = True)) then
begin
WriteLn('Expected a nonempty host in the JSON.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('access_token') <> 1) or (sharepointToken.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
// Configure host independently; never trust a response URL to choose a new credential audience.
if ((serviceHost.ContentsEqual(sharepointToken.StringOf('host'),False) = True) and (serviceUrl.Port = 443)) then
begin
downloadHttp.AuthToken := sharepointToken.StringOf('access_token');
end;
end;
end;
end;
// Without a matching token, only a still-valid preauthenticated URL can succeed.
downloadHttp.SetRequestHeader('Accept','*/*');
downloadHttp.SetRequestHeader('Accept-Encoding','identity');
success := downloadHttp.HttpNoBody('GET',downloadUrl,resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
end;
// A partial transfer can have status 200 but a false transport result. Never publish its bytes.
if (success <> True) then
begin
WriteLn('Content transfer did not complete; do not use its partial data.');
Exit;
end;
fileData := TBinData.Create;
success := resp.GetBodyBd(fileData);
if (success <> True) then
begin
WriteLn('Could not retrieve the downloaded bytes.');
Exit;
end;
actualSize := TStringBuilder.Create;
actualSize.AppendInt(fileData.NumBytes);
// Ask for identity encoding so Content-Length can be compared to the stored file bytes.
contentEncoding := TStringBuilder.Create;
contentEncoding.Append(resp.GetHeaderField('Content-Encoding'));
contentEncoding.Trim();
if ((contentEncoding.Length > 0) and (contentEncoding.ContentsEqual('identity',False) <> True)) then
begin
WriteLn('Unexpected content encoding; do not use this response as the file.');
Exit;
end;
declaredLength := TStringBuilder.Create;
declaredLength.Append(resp.GetHeaderField('Content-Length'));
declaredLength.Trim();
if (declaredLength.Length > 0) then
begin
lengthMatch := TJsonObject.Create;
lengthMatched := declaredLength.RegexMatch('\A[0-9]+\z',lengthMatch,100);
if (lengthMatched <> 1) then
begin
WriteLn('Invalid Content-Length; do not use this response as the file.');
Exit;
end;
// Compare decimal strings rather than narrowing a large file length to int.
while ((declaredLength.Length > 1) and (declaredLength.StartsWith('0',True) = True)) do
begin
declaredLength.RemoveCharsAt(0,1);
end;
if (declaredLength.ContentsEqual(actualSize.GetAsString(),True) <> True) then
begin
WriteLn('Content transfer did not complete: byte count differs from Content-Length.');
Exit;
end;
end;
WriteLn('Downloaded bytes: ' + fileData.NumBytes);
// Use fileData directly without text conversion; an empty file is valid.
token.Free;
http.Free;
resp.Free;
result.Free;
endpoint.Free;
serviceUrl.Free;
downloadHttp.Free;
serviceHost.Free;
serviceQuery.Free;
authMatch.Free;
tokenFiles.Free;
sharepointToken.Free;
fileData.Free;
actualSize.Free;
contentEncoding.Free;
declaredLength.Free;
lengthMatch.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.