S3: Delete Multiple Objects and Check Per-Object Errors
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.
Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.
The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.
Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.
Chilkat CkJava Downloads
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";
CkXml deleteRequest = new CkXml();
deleteRequest.put_Tag("Delete");
deleteRequest.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
deleteRequest.UpdateChildContent("Quiet","true");
// XML APIs escape key text. Do NOT URL-encode keys in this XML body.
deleteRequest.UpdateChildContent("Object[0]|Key","images/seahorse.jpg");
deleteRequest.UpdateChildContent("Object[1]|Key","images/starfish.jpg");
// For permanent deletion of a specific version, add Object[i]|VersionId
// deliberately. Use separate XML elements, not an embedded string convention.
if ((deleteRequest.NumChildrenHavingTag("Object") < 1) || (deleteRequest.NumChildrenHavingTag("Object") > 1000)) {
System.out.println("Use a batch of 1 to 1,000 object identifiers.");
return;
}
String requestBody = deleteRequest.getXml();
// 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(bucketName);
host.Append(".");
host.Append(endpoint.getAsString());
CkDateTime now = new CkDateTime();
success = now.SetFromCurrentSystemTime();
if (success != true) {
System.out.println("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) {
System.out.println("Could not hash delete body.");
return;
}
crypt.put_HashAlgorithm("sha256");
crypt.put_EncodingMode("hexlower");
String payloadHash = crypt.hashStringENC(requestBody);
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("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) {
signedHeaders.Append(";x-amz-security-token");
canonical.Append("x-amz-security-token:");
canonical.Append(credentials.stringOf("session_token"));
canonical.Append("\n");
http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"));
}
canonical.Append("\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append("\n");
canonical.Append(payloadHash);
String canonicalHash = crypt.hashStringENC(canonical.getAsString());
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("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) {
System.out.println("Could not set signing key.");
return;
}
String derivedKey = crypt.macStringENC(dateStamp);
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("Could not derive date signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
System.out.println("Could not set derived signing key.");
return;
}
derivedKey = crypt.macStringENC(region);
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
System.out.println("Could not set derived signing key.");
return;
}
derivedKey = crypt.macStringENC("s3");
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
System.out.println("Could not set derived signing key.");
return;
}
derivedKey = crypt.macStringENC("aws4_request");
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
System.out.println("Could not set final signing key.");
return;
}
String signature = crypt.macStringENC(stringToSign.getAsString());
if (crypt.get_LastMethodSuccess() != true) {
System.out.println("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);
http.SetRequestHeader("Authorization",authorization.getAsString());
http.SetRequestHeader("Content-MD5",contentMd5);
http.SetRequestHeader("x-amz-content-sha256",payloadHash);
http.SetRequestHeader("x-amz-date",amzDate);
CkStringBuilder requestUrl = new CkStringBuilder();
requestUrl.Append("https://");
requestUrl.Append(host.getAsString());
requestUrl.Append("/?delete=");
CkHttpResponse response = new CkHttpResponse();
success = http.HttpStr("POST",requestUrl.getAsString(),requestBody,"utf-8","application/xml",response);
if (success != true) {
System.out.println("Request failed (transport or S3 error). HTTP status: " + http.get_LastStatus());
// Inspect LastErrorText privately. Do not log credentials or signed URLs.
return;
}
if (response.get_StatusCode() != 200) {
System.out.println("Unexpected HTTP status: " + response.get_StatusCode());
return;
}
// HTTP 200 can contain per-object errors. Inspect the actual XML body.
CkXml xml = new CkXml();
success = xml.LoadXml(response.bodyStr());
if (success != true) {
System.out.println("Invalid XML response.");
return;
}
stringCompare.SetString(xml.tag());
boolean stringMatch4 = stringCompare.ContentsEqual("DeleteResult",true);
if (stringMatch4 != true) {
System.out.println("Unexpected XML response root.");
return;
}
int failures = xml.NumChildrenHavingTag("Error");
int i = 0;
while ((i < failures)) {
xml.put_I(i);
System.out.println("Failed key: " + xml.getChildContent("Error[i]|Key"));
System.out.println("Error code: " + xml.getChildContent("Error[i]|Code"));
i = i+1;
}
if (failures != 0) {
System.out.println("One or more objects were not deleted. Retry only appropriate failed identifiers.");
return;
}
// Quiet=true means success entries need not be returned.
System.out.println("Delete batch succeeded with no reported object errors.");
}
}