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

Amazon S3: Delete Multiple Objects and Check Each Result

See more S3 - REST Examples

Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.

Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.

General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS DeleteObjects reference

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    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;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the S3 operation.
    CkJsonObject credentials = new CkJsonObject();
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        Log.i(TAG, "Could not load private AWS credentials.");
        return;
        }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("access_key"));
    boolean sameText1 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) or (sameText1 == true)) {
        Log.i(TAG, "Missing or invalid access_key.");
        return;
        }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("secret_key"));
    boolean sameText2 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) or (sameText2 == true)) {
        Log.i(TAG, "Missing or invalid secret_key.");
        return;
        }

    //  General purpose bucket in the commercial AWS partition.
    String region = "us-west-2";
    String bucketName = "amzn-s3-demo-bucket";
    CkStringBuilder endpoint = new CkStringBuilder();
    success = endpoint.Append(bucketName);
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    success = endpoint.Append(".");
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    success = endpoint.Append("s3.");
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    success = endpoint.Append(region);
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    success = endpoint.Append(".amazonaws.com");
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    //  Connect to the SAME hostname used for TLS verification and request signing.
    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) {
        Log.i(TAG, "TLS connection failed; inspect diagnostics privately.");
        return;
        }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        Log.i(TAG, "Could not attach the TLS connection.");
        return;
        }

    CkXml xml = new CkXml();
    xml.put_Strict(true);
    rest.put_Host(endpoint.getAsString());
    if (credentials.HasMember("session_token") == true) {
        if (credentials.JsonTypeOf("session_token") != 1) {
            Log.i(TAG, "session_token must be a string.");
            return;
            }

        }

    //  One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
    CkJsonObject batch = new CkJsonObject();
    batch.put_Strict(true);
    success = batch.LoadFile("qa_data/aws/delete-objects.json");
    if (success != true) {
        Log.i(TAG, "Could not load the intended deletion batch.");
        return;
        }

    int count = batch.SizeOfArray("objects");
    if ((count < 1) or (count > 1000)) {
        Log.i(TAG, "Supply 1 to 1000 objects in the batch.");
        return;
        }

    xml.put_Tag("Delete");
    success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    xml.UpdateChildContent("Quiet","false");
    CkHashtable requested = new CkHashtable();
    CkJsonObject identity = new CkJsonObject();
    int i = 0;
    while ((i < count)) {
        batch.put_I(i);
        xml.put_I(i);
        textCompare.Clear();
        textCompare.SetString(batch.stringOf("objects[i].key"));
        boolean sameText3 = textCompare.ContentsEqual("",true);
        if ((batch.JsonTypeOf("objects[i].key") != 1) or (sameText3 == true)) {
            Log.i(TAG, "Each object needs a nonempty key.");
            return;
            }

        String key = batch.stringOf("objects[i].key");
        String version = "";
        if (batch.HasMember("objects[i].version_id") == true) {
            textCompare.Clear();
            textCompare.SetString(batch.stringOf("objects[i].version_id"));
            boolean sameText4 = textCompare.ContentsEqual("",true);
            if ((batch.JsonTypeOf("objects[i].version_id") != 1) or (sameText4 == true)) {
                Log.i(TAG, "version_id must be a nonempty string when present.");
                return;
                }

            version = batch.stringOf("objects[i].version_id");
            xml.UpdateChildContent("Object[i]|VersionId",version);
            }

        xml.UpdateChildContent("Object[i]|Key",key);
        success = identity.UpdateString("key",key);
        if (success != true) {
            Log.i(TAG, "Could not build saved state.");
            return;
            }

        success = identity.UpdateString("version",version);
        if (success != true) {
            Log.i(TAG, "Could not build saved state.");
            return;
            }

        String requestIdentity = identity.emit();
        if (requested.Contains(requestIdentity) == true) {
            Log.i(TAG, "Duplicate key/version in deletion batch.");
            return;
            }

        success = requested.AddInt(requestIdentity,1);
        if (success != true) {
            Log.i(TAG, "Could not prepare the request.");
            return;
            }

        i = i + 1;
        }

    String requestBody = xml.getXml();
    //  Explicit signing is used only for this fixed request so Content-MD5 survives.
    //  Rest sends it; AuthAws must NOT also be configured on this Rest instance.
    //  Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
    //  Do not change signed headers, body, endpoint, or query after signing.
    CkStringBuilder host = new CkStringBuilder();
    host.Append(endpoint.getAsString());
    CkDateTime now = new CkDateTime();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Log.i(TAG, "Could not read system time.");
        return;
        }

    CkStringBuilder timestamp = new CkStringBuilder();
    timestamp.Append(now.getAsTimestamp(false));
    int removedDashes = timestamp.Replace("-","");
    int removedColons = timestamp.Replace(":","");
    String amzDate = timestamp.getAsString();
    String dateStamp = timestamp.getRange(0,8,false);
    CkCrypt2 crypt = new CkCrypt2();
    crypt.put_Charset("utf-8");
    crypt.put_HashAlgorithm("md5");
    crypt.put_EncodingMode("base64");
    String contentMd5 = crypt.hashStringENC(requestBody);
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not hash delete body.");
        return;
        }

    crypt.put_HashAlgorithm("sha256");
    crypt.put_EncodingMode("hexlower");
    String payloadHash = crypt.hashStringENC(requestBody);
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not hash delete body.");
        return;
        }

    CkStringBuilder signedHeaders = new CkStringBuilder();
    signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date");
    CkStringBuilder canonical = new CkStringBuilder();
    canonical.Append("POST\n/\ndelete=\ncontent-md5:");
    canonical.Append(contentMd5);
    canonical.Append("\nhost:");
    canonical.Append(host.getAsString());
    canonical.Append("\nx-amz-content-sha256:");
    canonical.Append(payloadHash);
    canonical.Append("\nx-amz-date:");
    canonical.Append(amzDate);
    canonical.Append("\n");
    if (credentials.HasMember("session_token") == true) {
        textCompare.Clear();
        textCompare.SetString(credentials.stringOf("session_token"));
        boolean sameText5 = textCompare.ContentsEqual("",true);
        if (sameText5 != true) {
            signedHeaders.Append(";x-amz-security-token");
            canonical.Append("x-amz-security-token:");
            canonical.Append(credentials.stringOf("session_token"));
            canonical.Append("\n");
            success = rest.AddHeader("x-amz-security-token",credentials.stringOf("session_token"));
            if (success != true) {
                Log.i(TAG, "Could not prepare the request.");
                return;
                }

            }

        }

    canonical.Append("\n");
    canonical.Append(signedHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(payloadHash);
    String canonicalHash = crypt.hashStringENC(canonical.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not hash canonical request.");
        return;
        }

    CkStringBuilder scope = new CkStringBuilder();
    scope.Append(dateStamp);
    scope.Append("/");
    scope.Append(region);
    scope.Append("/s3/aws4_request");
    CkStringBuilder stringToSign = new CkStringBuilder();
    stringToSign.Append("AWS4-HMAC-SHA256\n");
    stringToSign.Append(amzDate);
    stringToSign.Append("\n");
    stringToSign.Append(scope.getAsString());
    stringToSign.Append("\n");
    stringToSign.Append(canonicalHash);
    CkStringBuilder initialKey = new CkStringBuilder();
    initialKey.Append("AWS4");
    initialKey.Append(credentials.stringOf("secret_key"));
    crypt.put_MacAlgorithm("hmac");
    success = crypt.SetMacKeyString(initialKey.getAsString());
    if (success != true) {
        Log.i(TAG, "Could not set signing key.");
        return;
        }

    String derivedKey = crypt.macStringENC(dateStamp);
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not derive date signing key.");
        return;
        }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        Log.i(TAG, "Could not set derived signing key.");
        return;
        }

    derivedKey = crypt.macStringENC(region);
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not derive signing key.");
        return;
        }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        Log.i(TAG, "Could not set derived signing key.");
        return;
        }

    derivedKey = crypt.macStringENC("s3");
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not derive signing key.");
        return;
        }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        Log.i(TAG, "Could not set derived signing key.");
        return;
        }

    derivedKey = crypt.macStringENC("aws4_request");
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not derive signing key.");
        return;
        }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        Log.i(TAG, "Could not set final signing key.");
        return;
        }

    String signature = crypt.macStringENC(stringToSign.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not sign delete request.");
        return;
        }

    CkStringBuilder authorization = new CkStringBuilder();
    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);
    success = rest.AddHeader("Authorization",authorization.getAsString());
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("Content-MD5",contentMd5);
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("x-amz-content-sha256",payloadHash);
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    success = rest.AddHeader("x-amz-date",amzDate);
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    success = rest.AddQueryParam("delete","");
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    String responseBody = rest.fullRequestString("POST","/",requestBody);
    if (rest.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Request did not complete; inspect diagnostics privately.");
        return;
        }

    if (rest.get_ResponseStatusCode() != 200) {
        Log.i(TAG, "S3 HTTP status: " + String.valueOf(rest.get_ResponseStatusCode()));
        success = xml.LoadXml(responseBody);
        textCompare.Clear();
        textCompare.SetString(xml.tag());
        boolean sameText6 = textCompare.ContentsEqual("Error",true);
        if ((success == true) and (sameText6 == true)) {
            Log.i(TAG, "S3 error code: " + xml.getChildContent("Code"));
            }

        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        return;
        }

    success = xml.LoadXml(responseBody);
    if (success != true) {
        Log.i(TAG, "Expected well-formed XML.");
        return;
        }

    textCompare.Clear();
    textCompare.SetString(xml.tag());
    boolean sameText7 = textCompare.ContentsEqual("DeleteResult",true);
    if (sameText7 != true) {
        Log.i(TAG, "Unexpected S3 response element; this is not a successful result.");
        return;
        }

    int deleted = xml.NumChildrenHavingTag("Deleted");
    int failed = xml.NumChildrenHavingTag("Error");
    if (deleted + failed != count) {
        Log.i(TAG, "Incomplete result: reconcile every requested object before retrying.");
        return;
        }

    CkHashtable received = new CkHashtable();
    int resultType = 0;
    while ((resultType < 2)) {
        String itemTag = "Deleted";
        int resultCount = deleted;
        if (resultType == 1) {
            itemTag = "Error";
            resultCount = failed;
            }

        int j = 0;
        while ((j < resultCount)) {
            xml.put_I(j);
            CkStringBuilder itemPath = new CkStringBuilder();
            success = itemPath.Append(itemTag);
            if (success != true) {
                Log.i(TAG, "Could not build text.");
                return;
                }

            success = itemPath.Append("[i]");
            if (success != true) {
                Log.i(TAG, "Could not build text.");
                return;
                }

            CkXml item = xml.FindChild(itemPath.getAsString());
            if (xml.get_LastMethodSuccess() != true) {
                Log.i(TAG, "Missing deletion result entry.");
                return;
                }

            String resultKey = item.getChildContent("Key");
            String resultVersion = "";
            if (item.HasChildWithTag("VersionId") == true) {
                resultVersion = item.getChildContent("VersionId");
                }

            success = identity.UpdateString("key",resultKey);
            if (success != true) {
                Log.i(TAG, "Could not build saved state.");
                return;
                }

            success = identity.UpdateString("version",resultVersion);
            if (success != true) {
                Log.i(TAG, "Could not build saved state.");
                return;
                }

            String responseIdentity = identity.emit();
            if ((requested.Contains(responseIdentity) != true) or (received.Contains(responseIdentity) == true)) {
                Log.i(TAG, "Unexpected or duplicated deletion result; reconcile manually.");
                return;
                }

            success = received.AddInt(responseIdentity,1);
            if (success != true) {
                Log.i(TAG, "Could not prepare the request.");
                return;
                }

            Log.i(TAG, itemTag + ": " + resultKey);
            if (resultType == 1) {
                Log.i(TAG, "Error code: " + item.getChildContent("Code"));
                }

            j = j + 1;
            }

        resultType = resultType + 1;
        }

    if (failed > 0) {
        Log.i(TAG, "Batch has per-object failures. Do not retry successful entries.");
        return;
        }

    Log.i(TAG, "All requested deletions acknowledged.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}