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

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.

Microsoft documentation

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoToken
    Handle hoHttp
    Variant vResp
    Handle hoResp
    Handle hoResult
    String sDriveId
    String sItemId
    Handle hoEndpoint
    Handle hoFac
    Handle hoUuid
    String sLocalId
    Handle hoTarget
    String sFinalPath
    String sPartialPath
    Variant vStreamRequest
    Handle hoStreamRequest
    String sDownloadUrl
    Handle hoServiceUrl
    Handle hoDownloadHttp
    Handle hoServiceHost
    Handle hoServiceQuery
    Variant vAuthMatch
    Handle hoAuthMatch
    Integer iAuthMatched
Files    Handle hoTokenFiles
    Handle hoSharepointToken
    String sActualSize
    Handle hoContentEncoding
    Handle hoDeclaredLength
    Variant vLengthMatch
    Handle hoLengthMatch
    Integer iLengthMatched
    String sTemp1
    String sTemp2
    String sTemp3
    Integer iTemp1
    Integer iTemp2
    Boolean bTemp1
    Boolean bTemp2

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Obtain a delegated Graph token with this example's file permissions.
    //  See OneDrive OAuth2 with PKCE.
    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Set ComStrict Of hoToken To True
    Get ComLoadFile Of hoToken "qa_data/tokens/oneDrive.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load the private OneDrive token cache."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Expected a nonempty access_token in the JSON."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End
    Get ComStringOf Of hoToken "access_token" To sTemp1
    Set ComAuthToken Of hoHttp To sTemp1
    Set ComRequireSslCertVerify Of hoHttp To True
    Set ComFollowRedirects Of hoHttp To False
    Set ComConnectTimeout Of hoHttp To 20
    Set ComReadTimeout Of hoHttp To 120
    Send ComSetRequestHeader To hoHttp "Accept" "application/json"
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Move "YOUR_DRIVE_ID" To sDriveId
    Move "YOUR_ITEM_ID" To sItemId
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "https://graph.microsoft.com/v1.0/drives/" To iSuccess
    Get ComUrlEncode Of hoHttp sDriveId To sTemp1
    Get ComAppend Of hoEndpoint sTemp1 To iSuccess
    Get ComAppend Of hoEndpoint "/items/" To iSuccess
    Get ComUrlEncode Of hoHttp sItemId To sTemp1
    Get ComAppend Of hoEndpoint sTemp1 To iSuccess
    Get ComAppend Of hoEndpoint "/content" To iSuccess
    Send ComSetRequestHeader To hoHttp "Accept" "*/*"
    Send ComSetRequestHeader To hoHttp "Accept-Encoding" "identity"
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComDirEnsureExists Of hoFac "qa_output/oneDrive" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create the output directory."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatCrypt2)) To hoUuid
    If (Not(IsComObjectCreated(hoUuid))) Begin
        Send CreateComObject of hoUuid
    End
    Get ComGenerateUuid Of hoUuid To sLocalId
    Get ComLastMethodSuccess Of hoUuid To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Could not make a local filename."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoTarget
    If (Not(IsComObjectCreated(hoTarget))) Begin
        Send CreateComObject of hoTarget
    End
    Get ComAppend Of hoTarget "qa_output/oneDrive/" To iSuccess
    Get ComAppend Of hoTarget sLocalId To iSuccess
    Get ComAppend Of hoTarget ".bin" To iSuccess
    Get ComGetAsString Of hoTarget To sFinalPath
    Get ComAppend Of hoTarget ".part" To iSuccess
    Get ComGetAsString Of hoTarget To sPartialPath
    Get ComFileExists Of hoFac sFinalPath To bTemp1
    Get ComFileExists Of hoFac sPartialPath To bTemp2
    If (bTemp1 Or bTemp2) Begin
        Showln "A generated output path already exists; nothing overwritten."
        Procedure_Return
    End

    //  Stream even the initial Graph response; direct content can be arbitrarily large.
    Get Create (RefClass(cComChilkatHttpRequest)) To hoStreamRequest
    If (Not(IsComObjectCreated(hoStreamRequest))) Begin
        Send CreateComObject of hoStreamRequest
    End
    Set ComHttpVerb Of hoStreamRequest To "GET"
    Set ComStreamResponseBodyPath Of hoHttp To sPartialPath
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get pvComObject of hoStreamRequest to vStreamRequest
    Get pvComObject of hoResp to vResp
    Get ComHttpReq Of hoHttp sTemp1 vStreamRequest vResp To iSuccess
    Set ComStreamResponseBodyPath Of hoHttp To ""
    Get ComStatusCode Of hoResp To iTemp1
    If ((iSuccess <> True) And (iTemp1 = 0)) Begin
        Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    Get ComStatusCode Of hoResp To iTemp2
    If ((iTemp1 <> 200) And (iTemp2 <> 302)) Begin
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Unexpected HTTP status: " iTemp1
        Get ComGetHeaderField Of hoResp "request-id" To sTemp1
        Showln "Request ID: " sTemp1
        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 429) Begin
            Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
            Showln "Retry-After: " sTemp1
        End

        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    If (iTemp1 = 302) Begin
        Get ComGetHeaderField Of hoResp "Location" To sDownloadUrl
        Get Create (RefClass(cComChilkatUrl)) To hoServiceUrl
        If (Not(IsComObjectCreated(hoServiceUrl))) Begin
            Send CreateComObject of hoServiceUrl
        End
        Get ComParseUrl Of hoServiceUrl sDownloadUrl To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid returned service URL."
            Procedure_Return
        End

        Get ComSsl Of hoServiceUrl To bTemp1
        Get ComHost Of hoServiceUrl To sTemp1
        Get ComLogin Of hoServiceUrl To sTemp2
        Get ComPassword Of hoServiceUrl To sTemp3
        If ((bTemp1 <> True) Or (sTemp1 = "") Or (sTemp2 <> "") Or (sTemp3 <> "")) Begin
            Showln "Expected an HTTPS service URL without embedded login credentials."
            Procedure_Return
        End

        //  Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
        //  Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
        Get Create (RefClass(cComChilkatHttp)) To hoDownloadHttp
        If (Not(IsComObjectCreated(hoDownloadHttp))) Begin
            Send CreateComObject of hoDownloadHttp
        End
        Set ComRequireSslCertVerify Of hoDownloadHttp To True
        Set ComFollowRedirects Of hoDownloadHttp To False
        Set ComConnectTimeout Of hoDownloadHttp To 20
        Set ComReadTimeout Of hoDownloadHttp To 120
        Get Create (RefClass(cComChilkatStringBuilder)) To hoServiceHost
        If (Not(IsComObjectCreated(hoServiceHost))) Begin
            Send CreateComObject of hoServiceHost
        End
        Get ComHost Of hoServiceUrl To sTemp1
        Get ComAppend Of hoServiceHost sTemp1 To iSuccess
        Get Create (RefClass(cComChilkatStringBuilder)) To hoServiceQuery
        If (Not(IsComObjectCreated(hoServiceQuery))) Begin
            Send CreateComObject of hoServiceQuery
        End
        Get ComQuery Of hoServiceUrl To sTemp1
        Get ComAppend Of hoServiceQuery sTemp1 To iSuccess
        Get Create (RefClass(cComChilkatJsonObject)) To hoAuthMatch
        If (Not(IsComObjectCreated(hoAuthMatch))) Begin
            Send CreateComObject of hoAuthMatch
        End
        Get pvComObject of hoAuthMatch to vAuthMatch
        Get ComRegexMatch Of hoServiceQuery "(?i)(?:^|[?&])tempauth=[^&]+" vAuthMatch 100 To iAuthMatched
        If (iAuthMatched < 0) Begin
            Showln "Could not inspect the service URL query."
            Procedure_Return
        End

        //  tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
        If (iAuthMatched = 0) Begin
            Get ComContentsEqual Of hoServiceHost "graph.microsoft.com" False To bTemp1
            Get ComPort Of hoServiceUrl To iTemp1
            If ((bTemp1 = True) And (iTemp1 = 443)) Begin
                Get ComStringOf Of hoToken "access_token" To sTemp1
                Set ComAuthToken Of hoDownloadHttp To sTemp1
            End
            Else Begin
                Get Create (RefClass(cComCkFileAccess)) To hoTokenFiles
                If (Not(IsComObjectCreated(hoTokenFiles))) Begin
                    Send CreateComObject of hoTokenFiles
                End
                Get ComFileExists Of hoTokenFiles "qa_data/tokens/oneDrive-sharepoint.json" To bTemp1
                If (bTemp1 = True) Begin
                    Get Create (RefClass(cComChilkatJsonObject)) To hoSharepointToken
                    If (Not(IsComObjectCreated(hoSharepointToken))) Begin
                        Send CreateComObject of hoSharepointToken
                    End
                    Set ComStrict Of hoSharepointToken To True
                    Get ComLoadFile Of hoSharepointToken "qa_data/tokens/oneDrive-sharepoint.json" To iSuccess
                    If (iSuccess <> True) Begin
                        Showln "Could not read the private SharePoint token cache."
                        Procedure_Return
                    End

                    Get ComJsonTypeOf Of hoSharepointToken "host" To iTemp1
                    Get ComStringOfEquals Of hoSharepointToken "host" "" True To bTemp1
                    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
                        Showln "Expected a nonempty host in the JSON."
                        Procedure_Return
                    End

                    Get ComJsonTypeOf Of hoSharepointToken "access_token" To iTemp1
                    Get ComStringOfEquals Of hoSharepointToken "access_token" "" True To bTemp1
                    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
                        Showln "Expected a nonempty access_token in the JSON."
                        Procedure_Return
                    End

                    //  Configure host independently; never trust a response URL to choose a new credential audience.
                    Get ComContentsEqual Of hoServiceHost (ComStringOf(hoSharepointToken, "host")) False To bTemp1
                    Get ComPort Of hoServiceUrl To iTemp1
                    If ((bTemp1 = True) And (iTemp1 = 443)) Begin
                        Get ComStringOf Of hoSharepointToken "access_token" To sTemp1
                        Set ComAuthToken Of hoDownloadHttp To sTemp1
                    End

                End

            End

        End

        //  Without a matching token, only a still-valid preauthenticated URL can succeed.
        Send ComSetRequestHeader To hoDownloadHttp "Accept" "*/*"
        Send ComSetRequestHeader To hoDownloadHttp "Accept-Encoding" "identity"
        //  The second response overwrites the temporary redirect body; it is not appended.
        Set ComStreamResponseBodyPath Of hoDownloadHttp To sPartialPath
        Get pvComObject of hoStreamRequest to vStreamRequest
        Get pvComObject of hoResp to vResp
        Get ComHttpReq Of hoDownloadHttp sDownloadUrl vStreamRequest vResp To iSuccess
        Set ComStreamResponseBodyPath Of hoDownloadHttp To ""
        Get ComStatusCode Of hoResp To iTemp1
        If ((iSuccess <> True) And (iTemp1 = 0)) Begin
            Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
            Procedure_Return
        End

        Get ComStatusCode Of hoResp To iTemp1
        If ((iTemp1 <> 200)) Begin
            Get ComStatusCode Of hoResp To iTemp1
            Showln "Unexpected HTTP status: " iTemp1
            Get ComGetHeaderField Of hoResp "request-id" To sTemp1
            Showln "Request ID: " sTemp1
            Get ComStatusCode Of hoResp To iTemp1
            If (iTemp1 = 429) Begin
                Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
                Showln "Retry-After: " sTemp1
            End

            Procedure_Return
        End

    End

    //  A partial transfer can have status 200 but a false transport result. Never publish its bytes.
    If (iSuccess <> True) Begin
        Showln "Content transfer did not complete; do not use its partial data."
        Procedure_Return
    End

    Get ComFileSizeStr Of hoFac sPartialPath To sActualSize
    Get ComLastMethodSuccess Of hoFac To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Could not determine the downloaded file size."
        Procedure_Return
    End

    //  Ask for identity encoding so Content-Length can be compared to the stored file bytes.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoContentEncoding
    If (Not(IsComObjectCreated(hoContentEncoding))) Begin
        Send CreateComObject of hoContentEncoding
    End
    Get ComGetHeaderField Of hoResp "Content-Encoding" To sTemp1
    Get ComAppend Of hoContentEncoding sTemp1 To iSuccess
    Get ComTrim Of hoContentEncoding To iSuccess
    Get ComLength Of hoContentEncoding To iTemp1
    Get ComContentsEqual Of hoContentEncoding "identity" False To bTemp1
    If ((iTemp1 > 0) And (bTemp1 <> True)) Begin
        Showln "Unexpected content encoding; do not use this response as the file."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoDeclaredLength
    If (Not(IsComObjectCreated(hoDeclaredLength))) Begin
        Send CreateComObject of hoDeclaredLength
    End
    Get ComGetHeaderField Of hoResp "Content-Length" To sTemp1
    Get ComAppend Of hoDeclaredLength sTemp1 To iSuccess
    Get ComTrim Of hoDeclaredLength To iSuccess
    Get ComLength Of hoDeclaredLength To iTemp1
    If (iTemp1 > 0) Begin
        Get Create (RefClass(cComChilkatJsonObject)) To hoLengthMatch
        If (Not(IsComObjectCreated(hoLengthMatch))) Begin
            Send CreateComObject of hoLengthMatch
        End
        Get pvComObject of hoLengthMatch to vLengthMatch
        Get ComRegexMatch Of hoDeclaredLength "\A[0-9]+\z" vLengthMatch 100 To iLengthMatched
        If (iLengthMatched <> 1) Begin
            Showln "Invalid Content-Length; do not use this response as the file."
            Procedure_Return
        End

        //  Compare decimal strings rather than narrowing a large file length to int.
        While (((ComLength(hoDeclaredLength)) > 1) And ((ComStartsWith(hoDeclaredLength, "0", True)) = True))
            Get ComRemoveCharsAt Of hoDeclaredLength 0 1 To iSuccess
        Loop

        Get ComContentsEqual Of hoDeclaredLength sActualSize True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Content transfer did not complete: byte count differs from Content-Length."
            Procedure_Return
        End

    End

    Get ComFileRename Of hoFac sPartialPath sFinalPath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Download completed but final rename failed; retain the .part file."
        Procedure_Return
    End

    Showln "Saved file: " sFinalPath


End_Procedure