OneDrive: Download Text into a StringBuilder
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.
Retrieve the final bytes, decode them with an explicitly supplied character set (UTF-8 here), and populate a StringBuilder. HTTP content-type metadata does not override the chosen file encoding. The file and decoded text are buffered in memory. Use this only for known text formats and never automatically execute downloaded content.
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 PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Result
string ls_DriveId
string ls_ItemId
oleobject loo_Endpoint
string ls_DownloadUrl
oleobject loo_ServiceUrl
oleobject loo_DownloadHttp
oleobject loo_ServiceHost
oleobject loo_ServiceQuery
oleobject loo_AuthMatch
long li_AuthMatched
oleobject loo_TokenFiles
oleobject loo_SharepointToken
oleobject loo_FileData
oleobject loo_ActualSize
oleobject loo_ContentEncoding
oleobject loo_DeclaredLength
oleobject loo_LengthMatch
long li_LengthMatched
string ls_Charset
string ls_Decoded
oleobject loo_FileText
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Token
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_Token.Strict = 1
li_Success = loo_Token.LoadFile("qa_data/tokens/oneDrive.json")
if li_Success <> 1 then
Write-Debug "Could not load the private OneDrive token cache."
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Expected a nonempty access_token in the JSON."
destroy loo_Token
return
end if
loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")
loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Http.RequireSslCertVerify = 1
loo_Http.FollowRedirects = 0
loo_Http.ConnectTimeout = 20
loo_Http.ReadTimeout = 120
loo_Http.SetRequestHeader("Accept","application/json")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")
loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")
loo_Result.Strict = 1
ls_DriveId = "YOUR_DRIVE_ID"
ls_ItemId = "YOUR_ITEM_ID"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")
loo_Endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_DriveId))
loo_Endpoint.Append("/items/")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_ItemId))
loo_Endpoint.Append("/content")
loo_Http.SetRequestHeader("Accept","*/*")
loo_Http.SetRequestHeader("Accept-Encoding","identity")
li_Success = loo_Http.HttpNoBody("GET",loo_Endpoint.GetAsString(),loo_Resp)
if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
Write-Debug "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
return
end if
if (loo_Resp.StatusCode <> 200) AND (loo_Resp.StatusCode <> 302) then
Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
if loo_Resp.StatusCode = 429 then
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
return
end if
if loo_Resp.StatusCode = 302 then
ls_DownloadUrl = loo_Resp.GetHeaderField("Location")
loo_ServiceUrl = create oleobject
li_rc = loo_ServiceUrl.ConnectToNewObject("Chilkat.Url")
li_Success = loo_ServiceUrl.ParseUrl(ls_DownloadUrl)
if li_Success <> 1 then
Write-Debug "Invalid returned service URL."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
return
end if
if (loo_ServiceUrl.Ssl <> 1) OR (loo_ServiceUrl.Host = "") OR (loo_ServiceUrl.Login <> "") OR (loo_ServiceUrl.Password <> "") then
Write-Debug "Expected an HTTPS service URL without embedded login credentials."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
return
end if
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
loo_DownloadHttp = create oleobject
li_rc = loo_DownloadHttp.ConnectToNewObject("Chilkat.Http")
loo_DownloadHttp.RequireSslCertVerify = 1
loo_DownloadHttp.FollowRedirects = 0
loo_DownloadHttp.ConnectTimeout = 20
loo_DownloadHttp.ReadTimeout = 120
loo_ServiceHost = create oleobject
li_rc = loo_ServiceHost.ConnectToNewObject("Chilkat.StringBuilder")
loo_ServiceHost.Append(loo_ServiceUrl.Host)
loo_ServiceQuery = create oleobject
li_rc = loo_ServiceQuery.ConnectToNewObject("Chilkat.StringBuilder")
loo_ServiceQuery.Append(loo_ServiceUrl.Query)
loo_AuthMatch = create oleobject
li_rc = loo_AuthMatch.ConnectToNewObject("Chilkat.JsonObject")
li_AuthMatched = loo_ServiceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",loo_AuthMatch,100)
if li_AuthMatched < 0 then
Write-Debug "Could not inspect the service URL query."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
return
end if
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if li_AuthMatched = 0 then
if (loo_ServiceHost.ContentsEqual("graph.microsoft.com",0) = 1) AND (loo_ServiceUrl.Port = 443) then
loo_DownloadHttp.AuthToken = loo_Token.StringOf("access_token")
else
loo_TokenFiles = create oleobject
li_rc = loo_TokenFiles.ConnectToNewObject("Chilkat.FileAccess")
if loo_TokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = 1 then
loo_SharepointToken = create oleobject
li_rc = loo_SharepointToken.ConnectToNewObject("Chilkat.JsonObject")
loo_SharepointToken.Strict = 1
li_Success = loo_SharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
if li_Success <> 1 then
Write-Debug "Could not read the private SharePoint token cache."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_SharepointToken.JsonTypeOf("host") <> 1) OR (loo_SharepointToken.StringOfEquals("host","",1) = 1) then
Write-Debug "Expected a nonempty host in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_SharepointToken.JsonTypeOf("access_token") <> 1) OR (loo_SharepointToken.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Expected a nonempty access_token in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
// Configure host independently; never trust a response URL to choose a new credential audience.
if (loo_ServiceHost.ContentsEqual(loo_SharepointToken.StringOf("host"),0) = 1) AND (loo_ServiceUrl.Port = 443) then
loo_DownloadHttp.AuthToken = loo_SharepointToken.StringOf("access_token")
end if
end if
end if
end if
// Without a matching token, only a still-valid preauthenticated URL can succeed.
loo_DownloadHttp.SetRequestHeader("Accept","*/*")
loo_DownloadHttp.SetRequestHeader("Accept-Encoding","identity")
li_Success = loo_DownloadHttp.HttpNoBody("GET",ls_DownloadUrl,loo_Resp)
if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
Write-Debug "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_Resp.StatusCode <> 200) then
Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
if loo_Resp.StatusCode = 429 then
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
end if
// A partial transfer can have status 200 but a false transport result. Never publish its bytes.
if li_Success <> 1 then
Write-Debug "Content transfer did not complete; do not use its partial data."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
loo_FileData = create oleobject
li_rc = loo_FileData.ConnectToNewObject("Chilkat.BinData")
li_Success = loo_Resp.GetBodyBd(loo_FileData)
if li_Success <> 1 then
Write-Debug "Could not retrieve the downloaded bytes."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
return
end if
loo_ActualSize = create oleobject
li_rc = loo_ActualSize.ConnectToNewObject("Chilkat.StringBuilder")
loo_ActualSize.AppendInt(loo_FileData.NumBytes)
// Ask for identity encoding so Content-Length can be compared to the stored file bytes.
loo_ContentEncoding = create oleobject
li_rc = loo_ContentEncoding.ConnectToNewObject("Chilkat.StringBuilder")
loo_ContentEncoding.Append(loo_Resp.GetHeaderField("Content-Encoding"))
loo_ContentEncoding.Trim()
if (loo_ContentEncoding.Length > 0) AND (loo_ContentEncoding.ContentsEqual("identity",0) <> 1) then
Write-Debug "Unexpected content encoding; do not use this response as the file."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
return
end if
loo_DeclaredLength = create oleobject
li_rc = loo_DeclaredLength.ConnectToNewObject("Chilkat.StringBuilder")
loo_DeclaredLength.Append(loo_Resp.GetHeaderField("Content-Length"))
loo_DeclaredLength.Trim()
if loo_DeclaredLength.Length > 0 then
loo_LengthMatch = create oleobject
li_rc = loo_LengthMatch.ConnectToNewObject("Chilkat.JsonObject")
li_LengthMatched = loo_DeclaredLength.RegexMatch("\A[0-9]+\z",loo_LengthMatch,100)
if li_LengthMatched <> 1 then
Write-Debug "Invalid Content-Length; do not use this response as the file."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
destroy loo_DeclaredLength
destroy loo_LengthMatch
return
end if
// Compare decimal strings rather than narrowing a large file length to int.
do while ((loo_DeclaredLength.Length > 1) AND (loo_DeclaredLength.StartsWith("0",1) = 1))
loo_DeclaredLength.RemoveCharsAt(0,1)
loop
if loo_DeclaredLength.ContentsEqual(loo_ActualSize.GetAsString(),1) <> 1 then
Write-Debug "Content transfer did not complete: byte count differs from Content-Length."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
destroy loo_DeclaredLength
destroy loo_LengthMatch
return
end if
end if
// Choose the actual file encoding; Graph does not convert arbitrary files to text.
ls_Charset = "utf-8"
ls_Decoded = loo_FileData.GetString(ls_Charset)
if loo_FileData.LastMethodSuccess <> 1 then
Write-Debug "Could not decode the file using the specified character set."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
destroy loo_DeclaredLength
destroy loo_LengthMatch
return
end if
loo_FileText = create oleobject
li_rc = loo_FileText.ConnectToNewObject("Chilkat.StringBuilder")
li_Success = loo_FileText.Append(ls_Decoded)
if li_Success <> 1 then
Write-Debug "Could not populate the text buffer."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
destroy loo_DeclaredLength
destroy loo_LengthMatch
destroy loo_FileText
return
end if
Write-Debug "Text downloaded into fileText."
// Parse the known format; do not execute downloaded HTML or script.
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_ServiceUrl
destroy loo_DownloadHttp
destroy loo_ServiceHost
destroy loo_ServiceQuery
destroy loo_AuthMatch
destroy loo_TokenFiles
destroy loo_SharepointToken
destroy loo_FileData
destroy loo_ActualSize
destroy loo_ContentEncoding
destroy loo_DeclaredLength
destroy loo_LengthMatch
destroy loo_FileText