Java
Chilkat2 Java
S3 Add Tags to an Object
See more Amazon S3 (new) Examples
Demonstrates how to add one or more tags to an S3 object.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Rest rest = new Rest();
// Connect to the Amazon AWS REST server in the desired region.
// (for us-east-1, we use "s3.amazonaws.com", but for another region, such as us-west-2, we would use "s3-us-west-2.amazonaws.com")
boolean bTls = true;
int port = 443;
boolean bAutoReconnect = true;
rest.connect("s3.amazonaws.com", port, bTls, bAutoReconnect);
// Provide AWS credentials.
AuthAws authAws = new AuthAws();
authAws.setAccessKey("AWS_ACCESS_KEY");
authAws.setSecretKey("AWS_SECRET_KEY");
authAws.setServiceName("s3");
authAws.setRegion("us-east-1");
rest.setAuthAws(authAws);
// Set the bucket name via the HOST header.
// In this case, the bucket name is "chilkat100".
// Note that the Host header should use "bucketName.s3.amazonaws.com", not "bucketName.s3-us-east-1.amazonaws.com"
// The same applies to aother regions. The Host header should simply be <bucketName>.s3.amazonaws.com regardless of the region.
rest.setHost("chilkat100.s3.amazonaws.com");
Xml xml = new Xml();
xml.setTag("Tagging");
xml.updateChildContent("TagSet|Tag|Key", "plant");
xml.updateChildContent("TagSet|Tag|Value", "chili pepper");
StringBuilder sbRequestBody = new StringBuilder();
xml.getXmlSb(sbRequestBody);
// It is important to add the terminating "=" after the "?tagging".
StringBuilder sbResponse = new StringBuilder();
try {
rest.fullRequestSb("PUT", "/chiliPepper.gif?tagging=", sbRequestBody, sbResponse);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Response status code: " + rest.getResponseStatusCode());
// When successful, the S3 Storage service will respond with a 200 response code,
// with an XML body.
if (rest.getResponseStatusCode() != 200) {
// Examine the request/response to see what happened.
System.out.println("response status code = " + rest.getResponseStatusCode());
System.out.println("response status text = " + rest.getResponseStatusText());
System.out.println("response header: " + rest.getResponseHeader());
System.out.println("response body: " + sbResponse.getAsString());
System.out.println("---");
System.out.println("LastRequestStartLine: " + rest.getLastRequestStartLine());
System.out.println("LastRequestHeader: " + rest.getLastRequestHeader());
}
System.out.println(sbResponse.getAsString());
System.out.println("Success.");
}
}