Java AWS S3: Add a Set of Tags to an S3 Object

Back to Index

Adds a set of tags to an existing S3 object. This example adds tags to the object named "starfish.jpg" located in the bucket "chilkat100".

Documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTtagging.html

CURL Command

curl -X PUT https://chilkat100.s3.amazonaws.com/starfish.jpg?tagging \
  -d '<Tagging>
  <TagSet>
     <Tag>
       <Key>animal</Key>
       <Value>starfish</Value>
     </Tag>
  </TagSet>
</Tagging>'

Java Example

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[])
  {
    CkRest rest = new CkRest();
    boolean success;

    CkAuthAws authAws = new CkAuthAws();
    authAws.put_AccessKey("AWS_ACCESS_KEY");
    authAws.put_SecretKey("AWS_SECRET_KEY");
    authAws.put_Region("us-east-1");
    authAws.put_ServiceName("s3");
    rest.SetAuthAws(authAws);

    //  URL: https://chilkat100.s3.amazonaws.com/starfish.jpg?tagging
    boolean bTls = true;
    int port = 443;
    boolean bAutoReconnect = true;
    success = rest.Connect("chilkat100.s3.amazonaws.com",port,bTls,bAutoReconnect);
    if (success != true) {
        System.out.println("ConnectFailReason: " + rest.get_ConnectFailReason());
        System.out.println(rest.lastErrorText());
        return;
        }

    //  See the Online Tool for Generating XML Creation Code
    CkXml xml = new CkXml();
    xml.put_Tag("Tagging");
    xml.UpdateChildContent("TagSet|Tag|Key","animal");
    xml.UpdateChildContent("TagSet|Tag|Value","starfish");

    CkStringBuilder sbRequestBody = new CkStringBuilder();
    xml.GetXmlSb(sbRequestBody);
    CkStringBuilder sbResponseBody = new CkStringBuilder();
    success = rest.FullRequestSb("PUT","/starfish.jpg?tagging",sbRequestBody,sbResponseBody);
    if (success != true) {
        System.out.println(rest.lastErrorText());
        return;
        }

    int respStatusCode = rest.get_ResponseStatusCode();
    if (respStatusCode >= 400) {
        System.out.println("Response Status Code = " + respStatusCode);
        System.out.println("Response Header:");
        System.out.println(rest.responseHeader());
        System.out.println("Response Body:");
        System.out.println(sbResponseBody.getAsString());
        return;
        }
  }
}