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

S3 Http: Download an Object Byte Range

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.

HEAD selects the current object and captures its ETag and version ID when available. GET requests bytes=0-1048575 using If-Match and that version. Requires HTTP 206, exact Content-Range/Content-Length, matching ETag, and the actual 1 MiB file length. HTTP 200 (Range ignored), 412, and 416 never promote output. Use an object at least 1 MiB in size and unused output paths.

Ranges are inclusive object offsets. This example downloads a range of an S3 object directly; it is not a standalone Glacier retrieval job. A whole-object checksum is not a checksum of a range. Requires s3:GetObject/s3:GetObjectVersion and applicable KMS permissions; archived objects must already be restored.

AWS 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;

    CkStringBuilder stringCompare = new CkStringBuilder();
    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.
    //  Load private credentials; never put access keys or session tokens in source.
    CkJsonObject credentials = new CkJsonObject();
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        System.out.println("Could not load private S3 credentials.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("access_key"));
    boolean stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
        System.out.println("Missing or invalid access_key.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("secret_key"));
    boolean stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
        System.out.println("Missing or invalid secret_key.");
        return;
        }

    CkHttp http = new CkHttp();
    http.put_AwsAccessKey(credentials.stringOf("access_key"));
    http.put_AwsSecretKey(credentials.stringOf("secret_key"));
    if (credentials.HasMember("session_token") == true) {
        stringCompare.SetString(credentials.stringOf("session_token"));
        boolean stringMatch3 = stringCompare.ContentsEqual("",true);
        if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
            System.out.println("session_token must be a nonempty string when supplied.");
            return;
            }

        http.put_AwsSessionToken(credentials.stringOf("session_token"));
        }

    //  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
    //  Set the actual bucket region, not the caller's location.
    String region = "us-west-2";
    http.put_AwsRegion(region);
    CkStringBuilder endpoint = new CkStringBuilder();
    endpoint.Append("s3.");
    endpoint.Append(region);
    endpoint.Append(".amazonaws.com");
    http.put_AwsEndpoint(endpoint.getAsString());
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    //  A region redirect is not success. Correct the endpoint and signing region.
    String bucketName = "your-bucket-name";
    String objectKey = "examples/archive.bin";
    CkHttpResponse response = new CkHttpResponse();
    CkCrypt2 signer = new CkCrypt2();
    signer.put_Charset("utf-8");
    signer.put_HashAlgorithm("sha256");
    signer.put_EncodingMode("hexlower");
    signer.put_MacAlgorithm("hmac");
    CkDateTime now = new CkDateTime();
    CkStringBuilder timestamp = new CkStringBuilder();
    CkStringBuilder canonical = new CkStringBuilder();
    CkStringBuilder canonicalHeaders = new CkStringBuilder();
    CkStringBuilder signedHeaders = new CkStringBuilder();
    CkStringBuilder scope = new CkStringBuilder();
    CkStringBuilder stringToSign = new CkStringBuilder();
    CkStringBuilder signingKey = new CkStringBuilder();
    CkStringBuilder authorization = new CkStringBuilder();
    CkStringBuilder url = new CkStringBuilder();
    CkStringBuilder query = new CkStringBuilder();
    CkStringBuilder number = new CkStringBuilder();
    CkStringBuilder host = new CkStringBuilder();
    CkStringBuilder uri = new CkStringBuilder();
    CkXml xml = new CkXml();
    String amzDate;
    String dateStamp;
    String payloadHash;
    String canonicalHash;
    String derivedKey;
    String signature;
    int replaceCount;
    host.Append(bucketName);
    host.Append(".");
    host.Append(endpoint.getAsString());
    //  Encode the original key exactly once, preserving S3 path separators.
    uri.SetString(http.urlEncode(objectKey));
    replaceCount = uri.ReplaceNoCase("%2f","/");
    if ((uri.StartsWith("/",true) == true) || (uri.Contains("/../",true) == true) || (uri.Contains("/./",true) == true)) {
        System.out.println("Use a key without a leading slash or dot path segments for these examples.");
        return;
        }

    uri.Prepend("/");
    String versionId = "";
    String etag;
    String expectedSize;
    String returnedVersion;
    CkFileAccess files = new CkFileAccess();
    String finalPath = "qa_output/s3-download.bin";
    String partialPath = "qa_output/s3-download.bin.part";
    if ((files.FileExists(finalPath) == true) || (files.FileExists(partialPath) == true)) {
        System.out.println("Choose unused output paths.");
        return;
        }

    query.Clear();
    stringCompare.SetString(versionId);
    boolean stringMatch4 = stringCompare.ContentsEqual("",true);
    if (stringMatch4 != true) {
        if (query.get_Length() > 0) {
            query.Append("&");
            }

        query.Append("versionId=");
        query.Append(http.urlEncode(versionId));
        }

    http.ClearHeaders();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        System.out.println("Could not read system time.");
        return;
        }

    timestamp.SetString(now.getAsTimestamp(false));
    replaceCount = timestamp.Replace("-","");
    replaceCount = timestamp.Replace(":","");
    amzDate = timestamp.getAsString();
    dateStamp = timestamp.getRange(0,8,false);
    payloadHash = signer.hashStringENC("");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not hash payload.");
        return;
        }

    canonicalHeaders.Clear();
    signedHeaders.Clear();
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("host");
    canonicalHeaders.Append("host:");
    canonicalHeaders.Append(host.getAsString());
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("host",host.getAsString());
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("x-amz-content-sha256");
    canonicalHeaders.Append("x-amz-content-sha256:");
    canonicalHeaders.Append(payloadHash);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("x-amz-content-sha256",payloadHash);
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("x-amz-date");
    canonicalHeaders.Append("x-amz-date:");
    canonicalHeaders.Append(amzDate);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("x-amz-date",amzDate);
    if (credentials.HasMember("session_token") == true) {
        if (signedHeaders.get_Length() > 0) {
            signedHeaders.Append(";");
            }

        signedHeaders.Append("x-amz-security-token");
        canonicalHeaders.Append("x-amz-security-token:");
        canonicalHeaders.Append(credentials.stringOf("session_token"));
        canonicalHeaders.Append("\n");
        http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"));
        }

    canonical.Clear();
    canonical.Append("HEAD\n");
    canonical.Append(uri.getAsString());
    canonical.Append("\n");
    canonical.Append(query.getAsString());
    canonical.Append("\n");
    canonical.Append(canonicalHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(signedHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(payloadHash);
    canonicalHash = signer.hashStringENC(canonical.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not hash canonical request.");
        return;
        }

    scope.Clear();
    scope.Append(dateStamp);
    scope.Append("/");
    scope.Append(region);
    scope.Append("/s3/aws4_request");
    stringToSign.Clear();
    stringToSign.Append("AWS4-HMAC-SHA256\n");
    stringToSign.Append(amzDate);
    stringToSign.Append("\n");
    stringToSign.Append(scope.getAsString());
    stringToSign.Append("\n");
    stringToSign.Append(canonicalHash);
    signingKey.SetString("AWS4");
    signingKey.Append(credentials.stringOf("secret_key"));
    success = signer.SetMacKeyString(signingKey.getAsString());
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC(dateStamp);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC(region);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC("s3");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC("aws4_request");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    signature = signer.macStringENC(stringToSign.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not sign request.");
        return;
        }

    authorization.Clear();
    authorization.Append("AWS4-HMAC-SHA256 Credential=");
    authorization.Append(credentials.stringOf("access_key"));
    authorization.Append("/");
    authorization.Append(scope.getAsString());
    authorization.Append(", SignedHeaders=");
    authorization.Append(signedHeaders.getAsString());
    authorization.Append(", Signature=");
    authorization.Append(signature);
    http.SetRequestHeader("Authorization",authorization.getAsString());
    url.SetString("https://");
    url.Append(host.getAsString());
    url.Append(uri.getAsString());
    if (query.get_Length() > 0) {
        url.Append("?");
        url.Append(query.getAsString());
        }

    success = http.HttpNoBody("HEAD",url.getAsString(),response);
    if ((success != true) || (response.get_StatusCode() != 200)) {
        System.out.println("Request failed or returned unexpected HTTP status: " + response.get_StatusCode());
        //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        return;
        }

    etag = response.getHeaderField("ETag");
    stringCompare.SetString(etag);
    boolean stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
        System.out.println("Missing required response header ETag.");
        return;
        }

    expectedSize = response.getHeaderField("Content-Length");
    stringCompare.SetString(expectedSize);
    boolean stringMatch6 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
        System.out.println("Missing required response header Content-Length.");
        return;
        }

    returnedVersion = response.getHeaderField("x-amz-version-id");
    if (response.get_LastMethodSuccess() != true) {
        returnedVersion = "";
        }

    stringCompare.SetString(versionId);
    boolean stringMatch7 = stringCompare.ContentsEqual("",true);
    if (stringMatch7 == true) {
        versionId = returnedVersion;
        }
    else {
        stringCompare.SetString(returnedVersion);
        boolean stringMatch8 = stringCompare.ContentsEqual(versionId,true);
        if (stringMatch8 != true) {
            System.out.println("Unexpected object version.");
            return;
            }

        }

    //  Download the first 1 MiB of an object containing at least that many bytes.
    number.SetString(expectedSize);
    if ((number.get_Length() < 8) && (number.get_IntValue() < 1048576)) {
        System.out.println("Choose an object of at least 1 MiB for this fixed range example.");
        return;
        }

    query.Clear();
    stringCompare.SetString(versionId);
    boolean stringMatch9 = stringCompare.ContentsEqual("",true);
    if (stringMatch9 != true) {
        if (query.get_Length() > 0) {
            query.Append("&");
            }

        query.Append("versionId=");
        query.Append(http.urlEncode(versionId));
        }

    http.ClearHeaders();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        System.out.println("Could not read system time.");
        return;
        }

    timestamp.SetString(now.getAsTimestamp(false));
    replaceCount = timestamp.Replace("-","");
    replaceCount = timestamp.Replace(":","");
    amzDate = timestamp.getAsString();
    dateStamp = timestamp.getRange(0,8,false);
    payloadHash = signer.hashStringENC("");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not hash payload.");
        return;
        }

    canonicalHeaders.Clear();
    signedHeaders.Clear();
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("host");
    canonicalHeaders.Append("host:");
    canonicalHeaders.Append(host.getAsString());
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("host",host.getAsString());
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("if-match");
    canonicalHeaders.Append("if-match:");
    canonicalHeaders.Append(etag);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("if-match",etag);
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("range");
    canonicalHeaders.Append("range:");
    canonicalHeaders.Append("bytes=0-1048575");
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("range","bytes=0-1048575");
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("x-amz-content-sha256");
    canonicalHeaders.Append("x-amz-content-sha256:");
    canonicalHeaders.Append(payloadHash);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("x-amz-content-sha256",payloadHash);
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
        }

    signedHeaders.Append("x-amz-date");
    canonicalHeaders.Append("x-amz-date:");
    canonicalHeaders.Append(amzDate);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("x-amz-date",amzDate);
    if (credentials.HasMember("session_token") == true) {
        if (signedHeaders.get_Length() > 0) {
            signedHeaders.Append(";");
            }

        signedHeaders.Append("x-amz-security-token");
        canonicalHeaders.Append("x-amz-security-token:");
        canonicalHeaders.Append(credentials.stringOf("session_token"));
        canonicalHeaders.Append("\n");
        http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"));
        }

    canonical.Clear();
    canonical.Append("GET\n");
    canonical.Append(uri.getAsString());
    canonical.Append("\n");
    canonical.Append(query.getAsString());
    canonical.Append("\n");
    canonical.Append(canonicalHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(signedHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(payloadHash);
    canonicalHash = signer.hashStringENC(canonical.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not hash canonical request.");
        return;
        }

    scope.Clear();
    scope.Append(dateStamp);
    scope.Append("/");
    scope.Append(region);
    scope.Append("/s3/aws4_request");
    stringToSign.Clear();
    stringToSign.Append("AWS4-HMAC-SHA256\n");
    stringToSign.Append(amzDate);
    stringToSign.Append("\n");
    stringToSign.Append(scope.getAsString());
    stringToSign.Append("\n");
    stringToSign.Append(canonicalHash);
    signingKey.SetString("AWS4");
    signingKey.Append(credentials.stringOf("secret_key"));
    success = signer.SetMacKeyString(signingKey.getAsString());
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC(dateStamp);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC(region);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC("s3");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC("aws4_request");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        System.out.println("Could not set signing key.");
        return;
        }

    signature = signer.macStringENC(stringToSign.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not sign request.");
        return;
        }

    authorization.Clear();
    authorization.Append("AWS4-HMAC-SHA256 Credential=");
    authorization.Append(credentials.stringOf("access_key"));
    authorization.Append("/");
    authorization.Append(scope.getAsString());
    authorization.Append(", SignedHeaders=");
    authorization.Append(signedHeaders.getAsString());
    authorization.Append(", Signature=");
    authorization.Append(signature);
    http.SetRequestHeader("Authorization",authorization.getAsString());
    url.SetString("https://");
    url.Append(host.getAsString());
    url.Append(uri.getAsString());
    if (query.get_Length() > 0) {
        url.Append("?");
        url.Append(query.getAsString());
        }

    success = http.Download(url.getAsString(),partialPath);
    if (http.get_LastStatus() == 412) {
        System.out.println("Object changed; range was not downloaded.");
        return;
        }

    if (http.get_LastStatus() == 416) {
        System.out.println("Requested range is not satisfiable; inspect object size and offsets.");
        return;
        }

    if ((success != true) || (http.get_LastStatus() != 206)) {
        System.out.println("Request failed or returned unexpected HTTP status: " + http.get_LastStatus());
        //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        return;
        }

    CkMime received = new CkMime();
    success = received.LoadMime(http.lastResponseHeader());
    if (success != true) {
        System.out.println("Could not parse download headers.");
        return;
        }

    String actualRange;
    String actualEtag;
    String receivedLength;
    CkStringBuilder expectedRange = new CkStringBuilder();
    expectedRange.Append("bytes 0-1048575/");
    expectedRange.Append(expectedSize);
    actualRange = received.getHeaderField("Content-Range");
    stringCompare.SetString(actualRange);
    boolean stringMatch10 = stringCompare.ContentsEqual("",true);
    if ((received.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
        System.out.println("Missing download header Content-Range.");
        return;
        }

    receivedLength = received.getHeaderField("Content-Length");
    stringCompare.SetString(receivedLength);
    boolean stringMatch11 = stringCompare.ContentsEqual("",true);
    if ((received.get_LastMethodSuccess() != true) || (stringMatch11 == true)) {
        System.out.println("Missing download header Content-Length.");
        return;
        }

    actualEtag = received.getHeaderField("ETag");
    stringCompare.SetString(actualEtag);
    boolean stringMatch12 = stringCompare.ContentsEqual("",true);
    if ((received.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
        System.out.println("Missing download header ETag.");
        return;
        }

    stringCompare.SetString(actualRange);
    boolean stringMatch13 = stringCompare.ContentsEqual(expectedRange.getAsString(),true);
    stringCompare.SetString(receivedLength);
    boolean stringMatch14 = stringCompare.ContentsEqual("1048576",true);
    stringCompare.SetString(actualEtag);
    boolean stringMatch15 = stringCompare.ContentsEqual(etag,true);
    if ((stringMatch13 != true) || (stringMatch14 != true) || (stringMatch15 != true)) {
        System.out.println("Range response does not match the requested object bytes.");
        return;
        }

    String actualSize = files.fileSizeStr(partialPath);
    stringCompare.SetString(actualSize);
    boolean stringMatch16 = stringCompare.ContentsEqual("1048576",true);
    if ((files.get_LastMethodSuccess() != true) || (stringMatch16 != true)) {
        System.out.println("Range byte count mismatch.");
        return;
        }

    success = files.FileRename(partialPath,finalPath);
    if (success != true) {
        System.out.println("Range remains at the temporary path.");
        return;
        }

    System.out.println("Range download succeeded; byte count checked.");
    //  A whole-object checksum cannot be used to verify this partial range.
  }
}