Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Graph token with this example's file permissions.
-- See OneDrive OAuth2 with PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/oneDrive.json")
if not success then
    print("Could not load the private OneDrive token cache.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("Expected a nonempty access_token in the JSON.")
    return
end

local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 120
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local driveId = "YOUR_DRIVE_ID"
local itemId = "YOUR_ITEM_ID"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://graph.microsoft.com/v1.0/drives/")
endpoint:append(http:url_encode(driveId))
endpoint:append("/items/")
endpoint:append(http:url_encode(itemId))
endpoint:append("/content")
http:set_request_header("Accept", "*/*")
http:set_request_header("Accept-Encoding", "identity")
success = http:http_no_body("GET", endpoint:get_as_string(), resp)
if (not success) and (resp.status_code == 0) then
    print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
    return
end

if (resp.status_code ~= 200) and (resp.status_code ~= 302) then
    print("Unexpected HTTP status: " .. resp.status_code)
    print("Request ID: " .. resp:get_header_field("request-id"))
    if resp.status_code == 429 then
        print("Retry-After: " .. resp:get_header_field("Retry-After"))
    end

    return
end

if resp.status_code == 302 then
    local downloadUrl = resp:get_header_field("Location")
    local serviceUrl = chilkat.Url.new()
    success = serviceUrl:parse_url(downloadUrl)
    if not success then
        print("Invalid returned service URL.")
        return
    end

    if (not serviceUrl.ssl) or ((serviceUrl.host == "") or ((serviceUrl.login ~= "") or (serviceUrl.password ~= ""))) then
        print("Expected an HTTPS service URL without embedded login credentials.")
        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.
    local downloadHttp = chilkat.Http.new()
    downloadHttp.require_ssl_cert_verify = true
    downloadHttp.follow_redirects = false
    downloadHttp.connect_timeout = 20
    downloadHttp.read_timeout = 120
    local serviceHost = chilkat.StringBuilder.new()
    serviceHost:append(serviceUrl.host)
    local serviceQuery = chilkat.StringBuilder.new()
    serviceQuery:append(serviceUrl.query)
    local authMatch = chilkat.JsonObject.new()
    local authMatched = serviceQuery:regex_match("(?i)(?:^|[?&])tempauth=[^&]+", authMatch, 100)
    if authMatched < 0 then
        print("Could not inspect the service URL query.")
        return
    end

    -- tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
    if authMatched == 0 then
        if (serviceHost:contents_equal("graph.microsoft.com", false)) and (serviceUrl.port == 443) then
            downloadHttp.auth_token = token:string_of("access_token")
        else
            local tokenFiles = chilkat.FileAccess.new()
            if tokenFiles:file_exists("qa_data/tokens/oneDrive-sharepoint.json") then
                local sharepointToken = chilkat.JsonObject.new()
                sharepointToken.strict = true
                success = sharepointToken:load_file("qa_data/tokens/oneDrive-sharepoint.json")
                if not success then
                    print("Could not read the private SharePoint token cache.")
                    return
                end

                if (sharepointToken:json_type_of("host") ~= 1) or (sharepointToken:string_of_equals("host", "", true)) then
                    print("Expected a nonempty host in the JSON.")
                    return
                end

                if (sharepointToken:json_type_of("access_token") ~= 1) or (sharepointToken:string_of_equals("access_token", "", true)) then
                    print("Expected a nonempty access_token in the JSON.")
                    return
                end

                -- Configure host independently; never trust a response URL to choose a new credential audience.
                if (serviceHost:contents_equal(sharepointToken:string_of("host"), false)) and (serviceUrl.port == 443) then
                    downloadHttp.auth_token = sharepointToken:string_of("access_token")
                end
            end
        end
    end

    -- Without a matching token, only a still-valid preauthenticated URL can succeed.
    downloadHttp:set_request_header("Accept", "*/*")
    downloadHttp:set_request_header("Accept-Encoding", "identity")
    success = downloadHttp:http_no_body("GET", downloadUrl, resp)
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        return
    end

    if resp.status_code ~= 200 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        return
    end
end

-- A partial transfer can have status 200 but a false transport result. Never publish its bytes.
if not success then
    print("Content transfer did not complete; do not use its partial data.")
    return
end

local fileData = chilkat.BinData.new()
success = resp:get_body_bd(fileData)
if not success then
    print("Could not retrieve the downloaded bytes.")
    return
end

local actualSize = chilkat.StringBuilder.new()
actualSize:append_int(fileData.num_bytes)
-- Ask for identity encoding so Content-Length can be compared to the stored file bytes.
local contentEncoding = chilkat.StringBuilder.new()
contentEncoding:append(resp:get_header_field("Content-Encoding"))
contentEncoding:trim()
if (contentEncoding.length > 0) and (not contentEncoding:contents_equal("identity", false)) then
    print("Unexpected content encoding; do not use this response as the file.")
    return
end

local declaredLength = chilkat.StringBuilder.new()
declaredLength:append(resp:get_header_field("Content-Length"))
declaredLength:trim()
if declaredLength.length > 0 then
    local lengthMatch = chilkat.JsonObject.new()
    local lengthMatched = declaredLength:regex_match("\\A[0-9]+\\z", lengthMatch, 100)
    if lengthMatched ~= 1 then
        print("Invalid Content-Length; do not use this response as the file.")
        return
    end

    -- Compare decimal strings rather than narrowing a large file length to int.
    while (declaredLength.length > 1) and (declaredLength:starts_with("0", true)) do
        declaredLength:remove_chars_at(0, 1)
    end

    if not declaredLength:contents_equal(actualSize:get_as_string(), true) then
        print("Content transfer did not complete: byte count differs from Content-Length.")
        return
    end
end

-- Choose the actual file encoding; Graph does not convert arbitrary files to text.
local charset = "utf-8"
local decoded = fileData:get_string(charset)
if not fileData.last_method_success then
    print("Could not decode the file using the specified character set.")
    return
end

local fileText = chilkat.StringBuilder.new()
success = fileText:append(decoded)
if not success then
    print("Could not populate the text buffer.")
    return
end

print("Text downloaded into fileText.")
-- Parse the known format; do not execute downloaded HTML or script.