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

S3 Http: List Object Versions and Delete Markers

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.

Lists both Version and DeleteMarker entries, with prefix filtering, URL-decoded keys, and pagination using the pair NextKeyMarker/NextVersionIdMarker. A missing optional version marker is omitted; opaque version IDs, including literal null, are not decoded as object keys. Tracks complete cursor pairs and bounds pagination.

Requires s3:ListBucketVersions. Listing is read-only and not a single snapshot. Objects and delete markers are distinct; deleting a current marker may expose an older version.

AWS reference

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

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

        StringBuilder stringCompare = new StringBuilder();
        // 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.
        JsonObject credentials = new JsonObject();
        credentials.setStrict(true);
        try {
            credentials.loadFile("qa_data/aws/s3.json");
        } catch (ChilkatException e) {
            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)) {
            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)) {
            System.out.println("Missing or invalid secret_key.");
            return;
        }

        Http http = new Http();
        http.setAwsAccessKey(credentials.stringOf("access_key"));
        http.setAwsSecretKey(credentials.stringOf("secret_key"));
        if (credentials.hasMember("session_token")) {
            stringCompare.setString(credentials.stringOf("session_token"));
            boolean stringMatch3 = stringCompare.contentsEqual("", true);
            if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch3)) {
                System.out.println("session_token must be a nonempty string when supplied.");
                return;
            }

            http.setAwsSessionToken(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.setAwsRegion(region);
        StringBuilder endpoint = new StringBuilder();
        endpoint.append("s3.");
        endpoint.append(region);
        endpoint.append(".amazonaws.com");
        http.setAwsEndpoint(endpoint.getAsString());
        http.setRequireSslCertVerify(true);
        http.setFollowRedirects(false);
        // A region redirect is not success. Correct the endpoint and signing region.
        String bucketName = "your-bucket-name";
        HttpResponse response = new HttpResponse();
        Crypt2 signer = new Crypt2();
        signer.setCharset("utf-8");
        signer.setHashAlgorithm("sha256");
        signer.setEncodingMode("hexlower");
        signer.setMacAlgorithm("hmac");
        DateTime now = new DateTime();
        StringBuilder timestamp = new StringBuilder();
        StringBuilder canonical = new StringBuilder();
        StringBuilder canonicalHeaders = new StringBuilder();
        StringBuilder signedHeaders = new StringBuilder();
        StringBuilder scope = new StringBuilder();
        StringBuilder stringToSign = new StringBuilder();
        StringBuilder signingKey = new StringBuilder();
        StringBuilder authorization = new StringBuilder();
        StringBuilder url = new StringBuilder();
        StringBuilder query = new StringBuilder();
        StringBuilder number = new StringBuilder();
        StringBuilder host = new StringBuilder();
        StringBuilder uri = new StringBuilder();
        Xml xml = new Xml();
        String amzDate = "";
        String dateStamp = "";
        String payloadHash = "";
        String canonicalHash = "";
        String derivedKey = "";
        String signature = "";
        int replaceCount = 0;
        host.append(bucketName);
        host.append(".");
        host.append(endpoint.getAsString());
        uri.append("/");
        Hashtable seen = new Hashtable();
        boolean more = true;
        int page = 0;
        String marker = "";
        String truncated = "";
        String item = "";
        String keyMarker = "";
        String versionMarker = "";
        String prefix = "examples/";
        JsonObject cursor = new JsonObject();
        while (more) {
            if (page == 10000) {
                System.out.println("Page bound reached; results are incomplete.");
                return;
            }

            page = page + 1;
            query.clear();
            if (query.getLength() > 0) {
                query.append("&");
            }

            query.append("encoding-type=");
            query.append(http.urlEncode("url"));
            stringCompare.setString(keyMarker);
            boolean stringMatch4 = stringCompare.contentsEqual("", true);
            if (!stringMatch4) {
                if (query.getLength() > 0) {
                    query.append("&");
                }

                query.append("key-marker=");
                query.append(http.urlEncode(keyMarker));
            }

            if (query.getLength() > 0) {
                query.append("&");
            }

            query.append("max-keys=");
            query.append(http.urlEncode("1000"));
            if (query.getLength() > 0) {
                query.append("&");
            }

            query.append("prefix=");
            query.append(http.urlEncode(prefix));
            stringCompare.setString(versionMarker);
            boolean stringMatch5 = stringCompare.contentsEqual("", true);
            if (!stringMatch5) {
                if (query.getLength() > 0) {
                    query.append("&");
                }

                query.append("version-id-marker=");
                query.append(http.urlEncode(versionMarker));
            }

            if (query.getLength() > 0) {
                query.append("&");
            }

            query.append("versions=");
            query.append(http.urlEncode(""));
            http.clearHeaders();
            try {
                now.setFromCurrentSystemTime();
            } catch (ChilkatException e) {
                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);
            try {
                payloadHash = signer.hashStringENC("");
            } catch (ChilkatException e) {
                System.out.println("Could not hash payload.");
                return;
            }

            canonicalHeaders.clear();
            signedHeaders.clear();
            if (signedHeaders.getLength() > 0) {
                signedHeaders.append(";");
            }

            signedHeaders.append("host");
            canonicalHeaders.append("host:");
            canonicalHeaders.append(host.getAsString());
            canonicalHeaders.append("\n");
            http.setRequestHeader("host", host.getAsString());
            if (signedHeaders.getLength() > 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.getLength() > 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")) {
                if (signedHeaders.getLength() > 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);
            try {
                canonicalHash = signer.hashStringENC(canonical.getAsString());
            } catch (ChilkatException e) {
                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"));
            try {
                signer.setMacKeyString(signingKey.getAsString());
            } catch (ChilkatException e) {
                System.out.println("Could not set signing key.");
                return;
            }

            try {
                derivedKey = signer.macStringENC(dateStamp);
            } catch (ChilkatException e) {
                System.out.println("Could not derive signing key.");
                return;
            }

            try {
                signer.setMacKeyEncoded(derivedKey, "hex");
            } catch (ChilkatException e) {
                System.out.println("Could not set signing key.");
                return;
            }

            try {
                derivedKey = signer.macStringENC(region);
            } catch (ChilkatException e) {
                System.out.println("Could not derive signing key.");
                return;
            }

            try {
                signer.setMacKeyEncoded(derivedKey, "hex");
            } catch (ChilkatException e) {
                System.out.println("Could not set signing key.");
                return;
            }

            try {
                derivedKey = signer.macStringENC("s3");
            } catch (ChilkatException e) {
                System.out.println("Could not derive signing key.");
                return;
            }

            try {
                signer.setMacKeyEncoded(derivedKey, "hex");
            } catch (ChilkatException e) {
                System.out.println("Could not set signing key.");
                return;
            }

            try {
                derivedKey = signer.macStringENC("aws4_request");
            } catch (ChilkatException e) {
                System.out.println("Could not derive signing key.");
                return;
            }

            try {
                signer.setMacKeyEncoded(derivedKey, "hex");
            } catch (ChilkatException e) {
                System.out.println("Could not set signing key.");
                return;
            }

            try {
                signature = signer.macStringENC(stringToSign.getAsString());
            } catch (ChilkatException e) {
                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.getLength() > 0) {
                url.append("?");
                url.append(query.getAsString());
            }

            try {
                http.httpNoBody("GET", url.getAsString(), response);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if ((!success) || (response.getStatusCode() != 200)) {
                System.out.println("Request failed or returned unexpected HTTP status: " + response.getStatusCode());
                // Preserve progress. Inspect full diagnostics privately; do not log secrets.
                return;
            }

            try {
                xml.loadXml(response.getBodyStr());
            } catch (ChilkatException e) {
                System.out.println("Invalid XML response.");
                return;
            }

            stringCompare.setString(xml.getTag());
            boolean stringMatch6 = stringCompare.contentsEqual("ListVersionsResult", true);
            if (!stringMatch6) {
                System.out.println("Unexpected XML result, possibly an embedded S3 error. Inspect privately.");
                return;
            }

            stringCompare.setString(xml.getChildContent("EncodingType"));
            boolean stringMatch7 = stringCompare.contentsEqual("url", true);
            if (!stringMatch7) {
                System.out.println("Expected URL encoding.");
                return;
            }

            int i = 0;
            while (i < xml.numChildrenHavingTag("Version")) {
                xml.setI(i);
                item = xml.getChildContent("Version[i]|Key");
                stringCompare.setString(item);
                boolean stringMatch8 = stringCompare.contentsEqual("", true);
                if ((!xml.getLastMethodSuccess()) || (stringMatch8)) {
                    System.out.println("Missing required Version[i]|Key.");
                    return;
                }

                System.out.println("Version key: " + http.urlDecode(item));
                item = xml.getChildContent("Version[i]|VersionId");
                stringCompare.setString(item);
                boolean stringMatch9 = stringCompare.contentsEqual("", true);
                if ((!xml.getLastMethodSuccess()) || (stringMatch9)) {
                    System.out.println("Missing required Version[i]|VersionId.");
                    return;
                }

                System.out.println("Version ID: " + item);
                System.out.println("Latest: " + xml.getChildContent("Version[i]|IsLatest"));
                i = i + 1;
            }

            int j = 0;
            while (j < xml.numChildrenHavingTag("DeleteMarker")) {
                xml.setI(j);
                item = xml.getChildContent("DeleteMarker[i]|Key");
                stringCompare.setString(item);
                boolean stringMatch10 = stringCompare.contentsEqual("", true);
                if ((!xml.getLastMethodSuccess()) || (stringMatch10)) {
                    System.out.println("Missing required DeleteMarker[i]|Key.");
                    return;
                }

                System.out.println("DeleteMarker key: " + http.urlDecode(item));
                item = xml.getChildContent("DeleteMarker[i]|VersionId");
                stringCompare.setString(item);
                boolean stringMatch11 = stringCompare.contentsEqual("", true);
                if ((!xml.getLastMethodSuccess()) || (stringMatch11)) {
                    System.out.println("Missing required DeleteMarker[i]|VersionId.");
                    return;
                }

                System.out.println("Version ID: " + item);
                System.out.println("Latest: " + xml.getChildContent("DeleteMarker[i]|IsLatest"));
                j = j + 1;
            }

            truncated = xml.getChildContent("IsTruncated");
            stringCompare.setString(truncated);
            boolean stringMatch12 = stringCompare.contentsEqual("", true);
            if ((!xml.getLastMethodSuccess()) || (stringMatch12)) {
                System.out.println("Missing required IsTruncated.");
                return;
            }

            stringCompare.setString(truncated);
            boolean stringMatch13 = stringCompare.contentsEqual("true", true);
            stringCompare.setString(truncated);
            boolean stringMatch14 = stringCompare.contentsEqual("false", true);
            if ((!stringMatch13) && (!stringMatch14)) {
                System.out.println("Invalid IsTruncated.");
                return;
            }

            more = false;
            stringCompare.setString(truncated);
            boolean stringMatch15 = stringCompare.contentsEqual("true", true);
            if (stringMatch15) {
                keyMarker = xml.getChildContent("NextKeyMarker");
                stringCompare.setString(keyMarker);
                boolean stringMatch16 = stringCompare.contentsEqual("", true);
                if ((!xml.getLastMethodSuccess()) || (stringMatch16)) {
                    System.out.println("Missing required NextKeyMarker.");
                    return;
                }

                keyMarker = http.urlDecode(keyMarker);
                versionMarker = "";
                if (xml.hasChildWithTag("NextVersionIdMarker")) {
                    versionMarker = xml.getChildContent("NextVersionIdMarker");
                }

                try {
                    cursor.updateString("key", keyMarker);
                } catch (ChilkatException e) {
                    System.out.println("Could not save key.");
                    return;
                }

                try {
                    cursor.updateString("version", versionMarker);
                } catch (ChilkatException e) {
                    System.out.println("Could not save version.");
                    return;
                }

                marker = cursor.emit();
                if (seen.contains(marker)) {
                    System.out.println("Repeated version cursor; listing is incomplete.");
                    return;
                }

                try {
                    seen.addStr(marker, "seen");
                } catch (ChilkatException e) {
                    System.out.println("Could not track version cursor.");
                    return;
                }

                more = true;
            }
        }

        System.out.println("Version and delete-marker listing complete.");
    }
}