Sample code for 30+ languages & platforms
Visual FoxPro Requires Chilkat v11.6.0+

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.

Microsoft documentation

Chilkat Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loToken
LOCAL loHttp
LOCAL loResp
LOCAL loResult
LOCAL lcDriveId
LOCAL lcItemId
LOCAL loEndpoint
LOCAL lcDownloadUrl
LOCAL loServiceUrl
LOCAL loDownloadHttp
LOCAL loServiceHost
LOCAL loServiceQuery
LOCAL loAuthMatch
LOCAL lnAuthMatched
LOCAL loTokenFiles
LOCAL loSharepointToken
LOCAL loFileData
LOCAL loActualSize
LOCAL loContentEncoding
LOCAL loDeclaredLength
LOCAL loLengthMatch
LOCAL lnLengthMatched
LOCAL lcCharset
LOCAL lcDecoded
LOCAL loFileText

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Obtain a delegated Graph token with this example's file permissions.
*  See OneDrive OAuth2 with PKCE.
loToken = CreateObject('Chilkat.JsonObject')
loToken.Strict = 1
lnSuccess = loToken.LoadFile("qa_data/tokens/oneDrive.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load the private OneDrive token cache."
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
    ? "Expected a nonempty access_token in the JSON."
    RELEASE loToken
    CANCEL
ENDIF

loHttp = CreateObject('Chilkat.Http')
loHttp.AuthToken = loToken.StringOf("access_token")
loHttp.RequireSslCertVerify = 1
loHttp.FollowRedirects = 0
loHttp.ConnectTimeout = 20
loHttp.ReadTimeout = 120
loHttp.SetRequestHeader("Accept","application/json")
loResp = CreateObject('Chilkat.HttpResponse')
loResult = CreateObject('Chilkat.JsonObject')
loResult.Strict = 1
lcDriveId = "YOUR_DRIVE_ID"
lcItemId = "YOUR_ITEM_ID"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("https://graph.microsoft.com/v1.0/drives/")
loEndpoint.Append(loHttp.UrlEncode(lcDriveId))
loEndpoint.Append("/items/")
loEndpoint.Append(loHttp.UrlEncode(lcItemId))
loEndpoint.Append("/content")
loHttp.SetRequestHeader("Accept","*/*")
loHttp.SetRequestHeader("Accept-Encoding","identity")
lnSuccess = loHttp.HttpNoBody("GET",loEndpoint.GetAsString(),loResp)
IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
    ? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    CANCEL
ENDIF

IF ((loResp.StatusCode <> 200) AND (loResp.StatusCode <> 302)) THEN
    ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
    ? "Request ID: " + loResp.GetHeaderField("request-id")
    IF (loResp.StatusCode = 429) THEN
        ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
    ENDIF

    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    CANCEL
ENDIF

IF (loResp.StatusCode = 302) THEN
    lcDownloadUrl = loResp.GetHeaderField("Location")
    loServiceUrl = CreateObject('Chilkat.Url')
    lnSuccess = loServiceUrl.ParseUrl(lcDownloadUrl)
    IF (lnSuccess <> 1) THEN
        ? "Invalid returned service URL."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        CANCEL
    ENDIF

    IF ((loServiceUrl.Ssl <> 1) OR (loServiceUrl.Host = "") OR (loServiceUrl.Login <> "") OR (loServiceUrl.Password <> "")) THEN
        ? "Expected an HTTPS service URL without embedded login credentials."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        CANCEL
    ENDIF

    *  Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
    *  Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
    loDownloadHttp = CreateObject('Chilkat.Http')
    loDownloadHttp.RequireSslCertVerify = 1
    loDownloadHttp.FollowRedirects = 0
    loDownloadHttp.ConnectTimeout = 20
    loDownloadHttp.ReadTimeout = 120
    loServiceHost = CreateObject('Chilkat.StringBuilder')
    loServiceHost.Append(loServiceUrl.Host)
    loServiceQuery = CreateObject('Chilkat.StringBuilder')
    loServiceQuery.Append(loServiceUrl.Query)
    loAuthMatch = CreateObject('Chilkat.JsonObject')
    lnAuthMatched = loServiceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",loAuthMatch,100)
    IF (lnAuthMatched < 0) THEN
        ? "Could not inspect the service URL query."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        RELEASE loDownloadHttp
        RELEASE loServiceHost
        RELEASE loServiceQuery
        RELEASE loAuthMatch
        CANCEL
    ENDIF

    *  tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
    IF (lnAuthMatched = 0) THEN
        IF ((loServiceHost.ContentsEqual("graph.microsoft.com",0) = 1) AND (loServiceUrl.Port = 443)) THEN
            loDownloadHttp.AuthToken = loToken.StringOf("access_token")
        ELSE
            loTokenFiles = CreateObject('Chilkat.FileAccess')
            IF (loTokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = 1) THEN
                loSharepointToken = CreateObject('Chilkat.JsonObject')
                loSharepointToken.Strict = 1
                lnSuccess = loSharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
                IF (lnSuccess <> 1) THEN
                    ? "Could not read the private SharePoint token cache."
                    RELEASE loToken
                    RELEASE loHttp
                    RELEASE loResp
                    RELEASE loResult
                    RELEASE loEndpoint
                    RELEASE loServiceUrl
                    RELEASE loDownloadHttp
                    RELEASE loServiceHost
                    RELEASE loServiceQuery
                    RELEASE loAuthMatch
                    RELEASE loTokenFiles
                    RELEASE loSharepointToken
                    CANCEL
                ENDIF

                IF ((loSharepointToken.JsonTypeOf("host") <> 1) OR (loSharepointToken.StringOfEquals("host","",1) = 1)) THEN
                    ? "Expected a nonempty host in the JSON."
                    RELEASE loToken
                    RELEASE loHttp
                    RELEASE loResp
                    RELEASE loResult
                    RELEASE loEndpoint
                    RELEASE loServiceUrl
                    RELEASE loDownloadHttp
                    RELEASE loServiceHost
                    RELEASE loServiceQuery
                    RELEASE loAuthMatch
                    RELEASE loTokenFiles
                    RELEASE loSharepointToken
                    CANCEL
                ENDIF

                IF ((loSharepointToken.JsonTypeOf("access_token") <> 1) OR (loSharepointToken.StringOfEquals("access_token","",1) = 1)) THEN
                    ? "Expected a nonempty access_token in the JSON."
                    RELEASE loToken
                    RELEASE loHttp
                    RELEASE loResp
                    RELEASE loResult
                    RELEASE loEndpoint
                    RELEASE loServiceUrl
                    RELEASE loDownloadHttp
                    RELEASE loServiceHost
                    RELEASE loServiceQuery
                    RELEASE loAuthMatch
                    RELEASE loTokenFiles
                    RELEASE loSharepointToken
                    CANCEL
                ENDIF

                *  Configure host independently; never trust a response URL to choose a new credential audience.
                IF ((loServiceHost.ContentsEqual(loSharepointToken.StringOf("host"),0) = 1) AND (loServiceUrl.Port = 443)) THEN
                    loDownloadHttp.AuthToken = loSharepointToken.StringOf("access_token")
                ENDIF

            ENDIF

        ENDIF

    ENDIF

    *  Without a matching token, only a still-valid preauthenticated URL can succeed.
    loDownloadHttp.SetRequestHeader("Accept","*/*")
    loDownloadHttp.SetRequestHeader("Accept-Encoding","identity")
    lnSuccess = loDownloadHttp.HttpNoBody("GET",lcDownloadUrl,loResp)
    IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
        ? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        RELEASE loDownloadHttp
        RELEASE loServiceHost
        RELEASE loServiceQuery
        RELEASE loAuthMatch
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        CANCEL
    ENDIF

    IF ((loResp.StatusCode <> 200)) THEN
        ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
        ? "Request ID: " + loResp.GetHeaderField("request-id")
        IF (loResp.StatusCode = 429) THEN
            ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
        ENDIF

        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        RELEASE loDownloadHttp
        RELEASE loServiceHost
        RELEASE loServiceQuery
        RELEASE loAuthMatch
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        CANCEL
    ENDIF

ENDIF

*  A partial transfer can have status 200 but a false transport result. Never publish its bytes.
IF (lnSuccess <> 1) THEN
    ? "Content transfer did not complete; do not use its partial data."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loServiceUrl
    RELEASE loDownloadHttp
    RELEASE loServiceHost
    RELEASE loServiceQuery
    RELEASE loAuthMatch
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    CANCEL
ENDIF

loFileData = CreateObject('Chilkat.BinData')
lnSuccess = loResp.GetBodyBd(loFileData)
IF (lnSuccess <> 1) THEN
    ? "Could not retrieve the downloaded bytes."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loServiceUrl
    RELEASE loDownloadHttp
    RELEASE loServiceHost
    RELEASE loServiceQuery
    RELEASE loAuthMatch
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    RELEASE loFileData
    CANCEL
ENDIF

loActualSize = CreateObject('Chilkat.StringBuilder')
loActualSize.AppendInt(loFileData.NumBytes)
*  Ask for identity encoding so Content-Length can be compared to the stored file bytes.
loContentEncoding = CreateObject('Chilkat.StringBuilder')
loContentEncoding.Append(loResp.GetHeaderField("Content-Encoding"))
loContentEncoding.Trim()
IF ((loContentEncoding.Length > 0) AND (loContentEncoding.ContentsEqual("identity",0) <> 1)) THEN
    ? "Unexpected content encoding; do not use this response as the file."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loServiceUrl
    RELEASE loDownloadHttp
    RELEASE loServiceHost
    RELEASE loServiceQuery
    RELEASE loAuthMatch
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    RELEASE loFileData
    RELEASE loActualSize
    RELEASE loContentEncoding
    CANCEL
ENDIF

loDeclaredLength = CreateObject('Chilkat.StringBuilder')
loDeclaredLength.Append(loResp.GetHeaderField("Content-Length"))
loDeclaredLength.Trim()
IF (loDeclaredLength.Length > 0) THEN
    loLengthMatch = CreateObject('Chilkat.JsonObject')
    lnLengthMatched = loDeclaredLength.RegexMatch("\A[0-9]+\z",loLengthMatch,100)
    IF (lnLengthMatched <> 1) THEN
        ? "Invalid Content-Length; do not use this response as the file."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        RELEASE loDownloadHttp
        RELEASE loServiceHost
        RELEASE loServiceQuery
        RELEASE loAuthMatch
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        RELEASE loFileData
        RELEASE loActualSize
        RELEASE loContentEncoding
        RELEASE loDeclaredLength
        RELEASE loLengthMatch
        CANCEL
    ENDIF

    *  Compare decimal strings rather than narrowing a large file length to int.
    DO WHILE ((loDeclaredLength.Length > 1) AND (loDeclaredLength.StartsWith("0",1) = 1))
        loDeclaredLength.RemoveCharsAt(0,1)
    ENDDO
    IF (loDeclaredLength.ContentsEqual(loActualSize.GetAsString(),1) <> 1) THEN
        ? "Content transfer did not complete: byte count differs from Content-Length."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loServiceUrl
        RELEASE loDownloadHttp
        RELEASE loServiceHost
        RELEASE loServiceQuery
        RELEASE loAuthMatch
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        RELEASE loFileData
        RELEASE loActualSize
        RELEASE loContentEncoding
        RELEASE loDeclaredLength
        RELEASE loLengthMatch
        CANCEL
    ENDIF

ENDIF

*  Choose the actual file encoding; Graph does not convert arbitrary files to text.
lcCharset = "utf-8"
lcDecoded = loFileData.GetString(lcCharset)
IF (loFileData.LastMethodSuccess <> 1) THEN
    ? "Could not decode the file using the specified character set."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loServiceUrl
    RELEASE loDownloadHttp
    RELEASE loServiceHost
    RELEASE loServiceQuery
    RELEASE loAuthMatch
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    RELEASE loFileData
    RELEASE loActualSize
    RELEASE loContentEncoding
    RELEASE loDeclaredLength
    RELEASE loLengthMatch
    CANCEL
ENDIF

loFileText = CreateObject('Chilkat.StringBuilder')
lnSuccess = loFileText.Append(lcDecoded)
IF (lnSuccess <> 1) THEN
    ? "Could not populate the text buffer."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loServiceUrl
    RELEASE loDownloadHttp
    RELEASE loServiceHost
    RELEASE loServiceQuery
    RELEASE loAuthMatch
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    RELEASE loFileData
    RELEASE loActualSize
    RELEASE loContentEncoding
    RELEASE loDeclaredLength
    RELEASE loLengthMatch
    RELEASE loFileText
    CANCEL
ENDIF

? "Text downloaded into fileText."
*  Parse the known format; do not execute downloaded HTML or script.

RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loFileData
RELEASE loActualSize
RELEASE loContentEncoding
RELEASE loDeclaredLength
RELEASE loLengthMatch
RELEASE loFileText