OneDrive: Download a File to Disk
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.
Both the initial Graph request and any returned-URL request use HttpReq with Http.StreamResponseBodyPath to stream into a generated .part file. The redirect body is replaced by the actual content. Rename only after a complete HTTP 200 transfer, so errors and truncated responses never become the final file. A failed transfer may leave a private .part file for cleanup. The file content is not buffered in memory and supplied remote filenames are not used as local paths.
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 Objective-C Downloads
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoFileAccess.h>
#import <CkoCrypt2.h>
#import <CkoHttpRequest.h>
#import <CkoUrl.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/oneDrive.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load the private OneDrive token cache.");
return;
}
if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
return;
}
CkoHttp *http = [[CkoHttp alloc] init];
http.AuthToken = [token StringOf: @"access_token"];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:120];
[http SetRequestHeader: @"Accept" value: @"application/json"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
NSString *driveId = @"YOUR_DRIVE_ID";
NSString *itemId = @"YOUR_ITEM_ID";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[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" value: @"*/*"];
[http SetRequestHeader: @"Accept-Encoding" value: @"identity"];
CkoFileAccess *fac = [[CkoFileAccess alloc] init];
success = [fac DirEnsureExists: @"qa_output/oneDrive"];
if (success != YES) {
NSLog(@"%@",@"Could not create the output directory.");
return;
}
CkoCrypt2 *uuid = [[CkoCrypt2 alloc] init];
NSString *localId = [uuid GenerateUuid];
if (uuid.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not make a local filename.");
return;
}
CkoStringBuilder *target = [[CkoStringBuilder alloc] init];
[target Append: @"qa_output/oneDrive/"];
[target Append: localId];
[target Append: @".bin"];
NSString *finalPath = [target GetAsString];
[target Append: @".part"];
NSString *partialPath = [target GetAsString];
if ([fac FileExists: finalPath] || [fac FileExists: partialPath]) {
NSLog(@"%@",@"A generated output path already exists; nothing overwritten.");
return;
}
// Stream even the initial Graph response; direct content can be arbitrarily large.
CkoHttpRequest *streamRequest = [[CkoHttpRequest alloc] init];
streamRequest.HttpVerb = @"GET";
http.StreamResponseBodyPath = partialPath;
success = [http HttpReq: [endpoint GetAsString] request: streamRequest response: resp];
http.StreamResponseBodyPath = @"";
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
return;
}
if (([resp.StatusCode intValue] != 200) && ([resp.StatusCode intValue] != 302)) {
NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
if ([resp.StatusCode intValue] == 429) {
NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
}
return;
}
if ([resp.StatusCode intValue] == 302) {
NSString *downloadUrl = [resp GetHeaderField: @"Location"];
CkoUrl *serviceUrl = [[CkoUrl alloc] init];
success = [serviceUrl ParseUrl: downloadUrl];
if (success != YES) {
NSLog(@"%@",@"Invalid returned service URL.");
return;
}
if ((serviceUrl.Ssl != YES) || (serviceUrl.Host == @"") || (serviceUrl.Login != @"") || (serviceUrl.Password != @"")) {
NSLog(@"%@",@"Expected an HTTPS service URL without embedded login credentials.");
return;
}
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
CkoHttp *downloadHttp = [[CkoHttp alloc] init];
downloadHttp.RequireSslCertVerify = YES;
downloadHttp.FollowRedirects = NO;
downloadHttp.ConnectTimeout = [NSNumber numberWithInt:20];
downloadHttp.ReadTimeout = [NSNumber numberWithInt:120];
CkoStringBuilder *serviceHost = [[CkoStringBuilder alloc] init];
[serviceHost Append: serviceUrl.Host];
CkoStringBuilder *serviceQuery = [[CkoStringBuilder alloc] init];
[serviceQuery Append: serviceUrl.Query];
CkoJsonObject *authMatch = [[CkoJsonObject alloc] init];
int authMatched = [[serviceQuery RegexMatch: @"(?i)(?:^|[?&])tempauth=[^&]+" json: authMatch timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (authMatched < 0) {
NSLog(@"%@",@"Could not inspect the service URL query.");
return;
}
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if (authMatched == 0) {
if (([serviceHost ContentsEqual: @"graph.microsoft.com" caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
downloadHttp.AuthToken = [token StringOf: @"access_token"];
}
else {
CkoFileAccess *tokenFiles = [[CkoFileAccess alloc] init];
if ([tokenFiles FileExists: @"qa_data/tokens/oneDrive-sharepoint.json"] == YES) {
CkoJsonObject *sharepointToken = [[CkoJsonObject alloc] init];
sharepointToken.Strict = YES;
success = [sharepointToken LoadFile: @"qa_data/tokens/oneDrive-sharepoint.json"];
if (success != YES) {
NSLog(@"%@",@"Could not read the private SharePoint token cache.");
return;
}
if (([[sharepointToken JsonTypeOf: @"host"] intValue] != 1) || ([sharepointToken StringOfEquals: @"host" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty host in the JSON.");
return;
}
if (([[sharepointToken JsonTypeOf: @"access_token"] intValue] != 1) || ([sharepointToken StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
return;
}
// Configure host independently; never trust a response URL to choose a new credential audience.
if (([serviceHost ContentsEqual: [sharepointToken StringOf: @"host"] caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
downloadHttp.AuthToken = [sharepointToken StringOf: @"access_token"];
}
}
}
}
// Without a matching token, only a still-valid preauthenticated URL can succeed.
[downloadHttp SetRequestHeader: @"Accept" value: @"*/*"];
[downloadHttp SetRequestHeader: @"Accept-Encoding" value: @"identity"];
// The second response overwrites the temporary redirect body; it is not appended.
downloadHttp.StreamResponseBodyPath = partialPath;
success = [downloadHttp HttpReq: downloadUrl request: streamRequest response: resp];
downloadHttp.StreamResponseBodyPath = @"";
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
return;
}
if (([resp.StatusCode intValue] != 200)) {
NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
if ([resp.StatusCode intValue] == 429) {
NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
}
return;
}
}
// A partial transfer can have status 200 but a false transport result. Never publish its bytes.
if (success != YES) {
NSLog(@"%@",@"Content transfer did not complete; do not use its partial data.");
return;
}
NSString *actualSize = [fac FileSizeStr: partialPath];
if (fac.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not determine the downloaded file size.");
return;
}
// Ask for identity encoding so Content-Length can be compared to the stored file bytes.
CkoStringBuilder *contentEncoding = [[CkoStringBuilder alloc] init];
[contentEncoding Append: [resp GetHeaderField: @"Content-Encoding"]];
[contentEncoding Trim];
if (([contentEncoding.Length intValue] > 0) && ([contentEncoding ContentsEqual: @"identity" caseSensitive: NO] != YES)) {
NSLog(@"%@",@"Unexpected content encoding; do not use this response as the file.");
return;
}
CkoStringBuilder *declaredLength = [[CkoStringBuilder alloc] init];
[declaredLength Append: [resp GetHeaderField: @"Content-Length"]];
[declaredLength Trim];
if ([declaredLength.Length intValue] > 0) {
CkoJsonObject *lengthMatch = [[CkoJsonObject alloc] init];
int lengthMatched = [[declaredLength RegexMatch: @"\\A[0-9]+\\z" json: lengthMatch timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (lengthMatched != 1) {
NSLog(@"%@",@"Invalid Content-Length; do not use this response as the file.");
return;
}
// Compare decimal strings rather than narrowing a large file length to int.
while ((([declaredLength.Length intValue] > 1) && ([declaredLength StartsWith: @"0" caseSensitive: YES] == YES))) {
[declaredLength RemoveCharsAt: [NSNumber numberWithInt: 0] numChars: [NSNumber numberWithInt: 1]];
}
if ([declaredLength ContentsEqual: actualSize caseSensitive: YES] != YES) {
NSLog(@"%@",@"Content transfer did not complete: byte count differs from Content-Length.");
return;
}
}
success = [fac FileRename: partialPath newPath: finalPath];
if (success != YES) {
NSLog(@"%@",@"Download completed but final rename failed; retain the .part file.");
return;
}
NSLog(@"%@%@",@"Saved file: ",finalPath);