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

Azure Blob: Resume a Download with ETag Protection

See more Azure Cloud Storage Examples

Save the account, path, ETag and size in an immutable checkpoint, then append complete byte ranges to a private .part file. A later run uses the existing partial-file length as its offset and checks that HEAD still describes the same blob. Every range carries If-Match and must return the expected ETag, exact Content-Range, Content-Length and body size before any bytes are appended.

The demonstration bounds offsets to 2,000,000,000 bytes so it can use int arithmetic without overflow; this is not an Azure service limit. Sizes in checkpoints remain strings. Only the final successful transfer renames the partial output to the final filename. Empty blobs are handled without issuing an invalid range.

Use one process, an exclusive local destination and an unchanged partial file. The checkpoint does not independently hash or authenticate local content; do not point it at an unrelated file or reuse a partial file that was edited or suffered disk corruption. After a local write failure inspect or restart the partial file. On 412 or changed HEAD properties, preserve the previous partial output and start a new download separately instead of combining versions. A crash while initially publishing the checkpoint fails closed if state is incomplete.

Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.

Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.

Microsoft reference.

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  StringBuilder compares text by value in every generated language.
    CkStringBuilder textCompare = new CkStringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObject config = new CkJsonObject();
    config.put_Strict(true);
    success = config.LoadFile("qa_data/azure/storage.json");
    if (success != true) {
        System.out.println("Could not load private Azure configuration.");
        return;
        }

    textCompare.Clear();
    textCompare.SetString(config.stringOf("account"));
    boolean sameText1 = textCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("account") != 1) || (sameText1 == true)) {
        System.out.println("Supply the storage account name.");
        return;
        }

    //  access_key is the base64 account key, not a connection string or SAS.
    textCompare.Clear();
    textCompare.SetString(config.stringOf("access_key"));
    boolean sameText2 = textCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("access_key") != 1) || (sameText2 == true)) {
        System.out.println("Supply the base64 account access key.");
        return;
        }

    CkStringBuilder endpoint = new CkStringBuilder();
    success = endpoint.Append(config.stringOf("account"));
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    success = endpoint.Append(".blob.core.windows.net");
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    //  resourcePath is already URL-encoded. Encode each path segment once when adapting it.
    //  Keep slash separators; names and paths are case-sensitive.
    String resourcePath = "/examplecontainer/example.bin";
    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    CkAuthAzureStorage azAuth = new CkAuthAzureStorage();
    azAuth.put_Account(config.stringOf("account"));
    azAuth.put_AccessKey(config.stringOf("access_key"));
    azAuth.put_Service("Blob");
    azAuth.put_Scheme("SharedKey");
    azAuth.put_XMsVersion("2026-04-06");
    success = rest.SetAuthAzureStorage(azAuth);
    if (success != true) {
        System.out.println("Could not configure Shared Key signing.");
        return;
        }

    CkSocket connection = new CkSocket();
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        System.out.println("TLS connection failed; inspect diagnostics privately.");
        return;
        }

    //  Do not replay a write automatically after losing its response.
    success = rest.UseConnection(connection,false);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    String responseText;
    CkXml result = new CkXml();
    result.put_Strict(true);
    String partFile = "qa_output/resume.bin.part";
    String finalFile = "qa_output/resume.bin";
    String checkpointFile = "qa_data/azure/download-checkpoint.json";
    CkFileAccess files = new CkFileAccess();
    if (files.FileExists(finalFile) == true) {
        System.out.println("Choose a new final filename; existing output is preserved.");
        return;
        }

    responseText = rest.fullRequestNoBody("HEAD",resourcePath);
    if (rest.get_LastMethodSuccess() != true) {
        System.out.println("Request did not complete; outcome may be uncertain.");
        return;
        }

    if (rest.get_ResponseStatusCode() != 200) {
        System.out.println("HTTP status: " + rest.get_ResponseStatusCode());
        System.out.println("Azure error code: " + rest.responseHdrByName("x-ms-error-code"));
        System.out.println("Request ID: " + rest.responseHdrByName("x-ms-request-id"));
        //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
        return;
        }

    String etag = rest.responseHdrByName("ETag");
    textCompare.Clear();
    textCompare.SetString(etag);
    boolean sameText3 = textCompare.ContentsEqual("",true);
    if (sameText3 == true) {
        System.out.println("Missing blob ETag.");
        return;
        }

    String totalText = rest.responseHdrByName("Content-Length");
    CkStringBuilder totalValue = new CkStringBuilder();
    success = totalValue.Append(totalText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    if ((totalValue.get_Length() < 1) || (totalValue.get_Length() > 10)) {
        System.out.println("Invalid or oversized length for this bounded example.");
        return;
        }

    CkStringBuilder totalDigits = new CkStringBuilder();
    success = totalDigits.Append(totalText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    int totalRemoved = 0;
    totalRemoved = totalDigits.Replace("0","");
    totalRemoved = totalDigits.Replace("1","");
    totalRemoved = totalDigits.Replace("2","");
    totalRemoved = totalDigits.Replace("3","");
    totalRemoved = totalDigits.Replace("4","");
    totalRemoved = totalDigits.Replace("5","");
    totalRemoved = totalDigits.Replace("6","");
    totalRemoved = totalDigits.Replace("7","");
    totalRemoved = totalDigits.Replace("8","");
    totalRemoved = totalDigits.Replace("9","");
    if (totalDigits.get_Length() != 0) {
        System.out.println("Length must be a decimal string.");
        return;
        }

    if ((totalValue.get_Length() == 10) && (totalValue.StartsWith("1",true) != true) && (totalValue.ContentsEqual("2000000000",true) != true)) {
        System.out.println("Length exceeds the 2,000,000,000-byte demonstration bound.");
        return;
        }

    CkJsonObject totalNumber = new CkJsonObject();
    success = totalNumber.UpdateNumber("value",totalText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    int total = totalNumber.IntOf("value");
    CkJsonObject checkpoint = new CkJsonObject();
    checkpoint.put_Strict(true);
    if (files.FileExists(checkpointFile) == true) {
        success = checkpoint.LoadFile(checkpointFile);
        if (success != true) {
            System.out.println("Invalid checkpoint.");
            return;
            }

        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("path"));
        boolean sameText4 = textCompare.ContentsEqual(resourcePath,true);
        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("etag"));
        boolean sameText5 = textCompare.ContentsEqual(etag,true);
        textCompare.Clear();
        textCompare.SetString(checkpoint.stringOf("size"));
        boolean sameText6 = textCompare.ContentsEqual(totalText,true);
        if ((checkpoint.stringOf("account") != config.stringOf("account")) || (sameText4 != true) || (sameText5 != true) || (sameText6 != true)) {
            System.out.println("The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.");
            return;
            }

        }
    else {
        if (files.FileExists(partFile) == true) {
            System.out.println("Partial file exists without its checkpoint; refusing to append.");
            return;
            }

        success = checkpoint.UpdateString("account",config.stringOf("account"));
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = checkpoint.UpdateString("path",resourcePath);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = checkpoint.UpdateString("etag",etag);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = checkpoint.UpdateString("size",totalText);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = checkpoint.WriteFile("qa_data/azure/download-checkpoint.tmp");
        if (success != true) {
            System.out.println("Could not write checkpoint.");
            return;
            }

        success = files.FileRename("qa_data/azure/download-checkpoint.tmp",checkpointFile);
        if (success != true) {
            System.out.println("Could not publish checkpoint.");
            return;
            }

        }

    //  The immutable checkpoint identifies the version. Actual local length is the resume offset.
    //  Keep this partial file private, unchanged and exclusive to this one download.
    String localSize = "0";
    if (files.FileExists(partFile) == true) {
        localSize = files.fileSizeStr(partFile);
        if (files.get_LastMethodSuccess() != true) {
            System.out.println("Could not get partial-file size.");
            return;
            }

        }

    String offsetText = localSize;
    CkStringBuilder offsetValue = new CkStringBuilder();
    success = offsetValue.Append(offsetText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    if ((offsetValue.get_Length() < 1) || (offsetValue.get_Length() > 10)) {
        System.out.println("Invalid or oversized length for this bounded example.");
        return;
        }

    CkStringBuilder offsetDigits = new CkStringBuilder();
    success = offsetDigits.Append(offsetText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    int offsetRemoved = 0;
    offsetRemoved = offsetDigits.Replace("0","");
    offsetRemoved = offsetDigits.Replace("1","");
    offsetRemoved = offsetDigits.Replace("2","");
    offsetRemoved = offsetDigits.Replace("3","");
    offsetRemoved = offsetDigits.Replace("4","");
    offsetRemoved = offsetDigits.Replace("5","");
    offsetRemoved = offsetDigits.Replace("6","");
    offsetRemoved = offsetDigits.Replace("7","");
    offsetRemoved = offsetDigits.Replace("8","");
    offsetRemoved = offsetDigits.Replace("9","");
    if (offsetDigits.get_Length() != 0) {
        System.out.println("Length must be a decimal string.");
        return;
        }

    if ((offsetValue.get_Length() == 10) && (offsetValue.StartsWith("1",true) != true) && (offsetValue.ContentsEqual("2000000000",true) != true)) {
        System.out.println("Length exceeds the 2,000,000,000-byte demonstration bound.");
        return;
        }

    CkJsonObject offsetNumber = new CkJsonObject();
    success = offsetNumber.UpdateNumber("value",offsetText);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    int offset = offsetNumber.IntOf("value");
    if (offset > total) {
        System.out.println("Partial file is longer than the selected blob.");
        return;
        }

    //  Ensure an empty blob also creates a local file.
    success = files.OpenForAppend(partFile);
    if (success != true) {
        System.out.println("Could not open partial file.");
        return;
        }

    files.FileClose();
    success = rest.AddHeader("If-Match",etag);
    if (success != true) {
        System.out.println("Could not prepare the request.");
        return;
        }

    CkBinData chunk = new CkBinData();
    CkStringBuilder range = new CkStringBuilder();
    CkStringBuilder expectedRange = new CkStringBuilder();
    CkStringBuilder expectedLength = new CkStringBuilder();
    while ((offset < total)) {
        int count = total - offset;
        if (count > 4194304) {
            count = 4194304;
            }

        int endByte = offset+count - 1;
        range.Clear();
        success = range.Append("bytes=");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = range.AppendInt(offset);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = range.Append("-");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = range.AppendInt(endByte);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = rest.AddHeader("x-ms-range",range.getAsString());
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        expectedRange.Clear();
        success = expectedRange.Append("bytes ");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = expectedRange.AppendInt(offset);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = expectedRange.Append("-");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = expectedRange.AppendInt(endByte);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = expectedRange.Append("/");
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = expectedRange.Append(totalText);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        expectedLength.Clear();
        success = expectedLength.AppendInt(count);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        rest.Disconnect(10);
        success = connection.Connect(endpoint.getAsString(),443,true,20000);
        if (success != true) {
            System.out.println("TLS reconnection failed.");
            return;
            }

        success = rest.UseConnection(connection,false);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = rest.SendReqNoBody("GET",resourcePath);
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        int httpStatus = rest.ReadResponseHeader();
        if (httpStatus < 0) {
            System.out.println("Could not read range response headers.");
            return;
            }

        if (rest.get_ResponseStatusCode() != 206) {
            System.out.println("HTTP status: " + rest.get_ResponseStatusCode());
            System.out.println("Azure error code: " + rest.responseHdrByName("x-ms-error-code"));
            System.out.println("Request ID: " + rest.responseHdrByName("x-ms-request-id"));
            //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
            return;
            }

        textCompare.Clear();
        textCompare.SetString(rest.responseHdrByName("ETag"));
        boolean sameText7 = textCompare.ContentsEqual(etag,true);
        if ((sameText7 != true) || (rest.responseHdrByName("Content-Range") != expectedRange.getAsString()) || (rest.responseHdrByName("Content-Length") != expectedLength.getAsString())) {
            System.out.println("Unexpected range response; no bytes appended.");
            return;
            }

        success = chunk.Clear();
        if (success != true) {
            System.out.println("Could not prepare the request.");
            return;
            }

        success = rest.ReadRespBd(chunk);
        if (success != true) {
            System.out.println("Incomplete range body; no bytes appended.");
            return;
            }

        if (chunk.get_NumBytes() != count) {
            System.out.println("Wrong byte count; no bytes appended.");
            return;
            }

        success = files.OpenForAppend(partFile);
        if (success != true) {
            System.out.println("Could not reopen partial file.");
            return;
            }

        success = files.FileWriteBd(chunk,0,0);
        files.FileClose();
        if (success != true) {
            System.out.println("Local write failed. Inspect the partial file before retrying.");
            return;
            }

        offset = offset+count;
        }

    success = files.FileRename(partFile,finalFile);
    if (success != true) {
        System.out.println("Could not publish completed download.");
        return;
        }

    System.out.println("Download complete. Retain or archive the checkpoint with the completed file.");
  }
}