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

Amazon S3: Create or Replace an Object Conditionally

See more S3 - REST Examples

Create mode sends If-None-Match: * to avoid replacing an existing current object. Replace mode sends the exact quoted ETag recorded by the caller using If-Match. Requires s3:PutObject; If-Match can also require s3:GetObject. There is no fallback to an unconditional write.

HTTP 412 means the precondition failed; 409 indicates a conflicting concurrent operation. Re-read and reconcile before a bounded retry. In a versioned bucket, conditions concern the current version; a current delete marker can allow create mode to succeed. ETags are opaque validators, not necessarily MD5 hashes, and do not implement a transaction across multiple keys. A lost response leaves the outcome uncertain.

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 PutObject 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;
        }

    CkAuthAws aws = new CkAuthAws();
    aws.put_AccessKey(credentials.stringOf("access_key"));
    aws.put_SecretKey(credentials.stringOf("secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName("s3");
    aws.put_SignatureVersion(4);
    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        Log.i(TAG, "Could not configure AWS signing.");
        return;
        }

    //  Temporary credentials require this token in every signed query.
    //  Keep request URLs private. Do not clear this parameter between requests.
    if (credentials.HasMember("session_token") == true) {
        if (credentials.JsonTypeOf("session_token") != 1) {
            Log.i(TAG, "session_token must be a string.");
            return;
            }

        textCompare.Clear();
        textCompare.SetString(credentials.stringOf("session_token"));
        boolean sameText3 = textCompare.ContentsEqual("",true);
        if (sameText3 != true) {
            success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"));
            if (success != true) {
                Log.i(TAG, "Could not prepare the request.");
                return;
                }

            }

        }

    //  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);
    //  Supply an unencoded object key, not a URL. Preserve slashes in the key.
    String objectKey = "documents/example.txt";
    CkStringBuilder objectPath = new CkStringBuilder();
    success = objectPath.Append(objectKey);
    if (success != true) {
        Log.i(TAG, "Could not build text.");
        return;
        }

    success = objectPath.Encode("url_rfc3986","utf-8");
    if (success != true) {
        Log.i(TAG, "Could not encode the object key.");
        return;
        }

    int restoredSlashes = objectPath.Replace("%2F","/");
    success = objectPath.Prepend("/");
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    String operation = "create";
    //  For replace, use the exact quoted ETag from the version you intend to update.
    String expectedEtag = "YOUR_QUOTED_ETAG";
    textCompare.Clear();
    textCompare.SetString(operation);
    boolean sameText4 = textCompare.ContentsEqual("create",true);
    if (sameText4 == true) {
        success = rest.AddHeader("If-None-Match","*");
        if (success != true) {
            Log.i(TAG, "Could not prepare the request.");
            return;
            }

        }
    else {
        textCompare.Clear();
        textCompare.SetString(operation);
        boolean sameText5 = textCompare.ContentsEqual("replace",true);
        if (sameText5 != true) {
            Log.i(TAG, "Choose create or replace.");
            return;
            }

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

        }

    success = rest.AddHeader("Content-Type","text/plain; charset=utf-8");
    if (success != true) {
        Log.i(TAG, "Could not prepare the request.");
        return;
        }

    String responseBody = rest.fullRequestString("PUT",objectPath.getAsString(),"Updated text.\n");
    if (rest.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Write outcome is uncertain; inspect the object before retrying.");
        return;
        }

    if (rest.get_ResponseStatusCode() == 412) {
        Log.i(TAG, "Precondition failed; the requested write was not applied.");
        return;
        }

    if (rest.get_ResponseStatusCode() == 409) {
        Log.i(TAG, "Concurrent request conflict. Re-read state and apply a bounded retry policy.");
        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;
        }

    Log.i(TAG, "Conditional upload succeeded.");
    Log.i(TAG, "ETag: " + rest.responseHdrByName("ETag"));

  }

  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."
  }
}