Sample code for 30+ languages & platforms
Java

S3 List Buckets using an STS Session Token

See more AWS Security Token Service Examples

This is an example showing how to use an STS session token in an Amazon AWS request. This example will list S3 buckets using a previously obtained session token.

Chilkat Java Downloads

Chilkat2 Java
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.

        // See Get AWS STS Session Token for sample code to get the session token XML.
        Xml xmlToken = new Xml();
        try {
            xmlToken.loadXmlFile("qa_data/tokens/aws_session_token.xml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Rest rest = new Rest();

        // Connect to the Amazon AWS REST server.
        boolean bTls = true;
        int port = 443;
        boolean bAutoReconnect = true;
        rest.connect("s3.amazonaws.com", port, bTls, bAutoReconnect);

        // Provide AWS credentials for the REST call.
        AuthAws authAws = new AuthAws();

        // The purpose of this example is to show how to use the temporary AccessKeyId, SecretAccessKey, and SessionToken.
        authAws.setAccessKey(xmlToken.getChildContent("GetSessionTokenResult|Credentials|AccessKeyId"));
        authAws.setSecretKey(xmlToken.getChildContent("GetSessionTokenResult|Credentials|SecretAccessKey"));
        authAws.setServiceName("s3");
        rest.setAuthAws(authAws);

        rest.addQueryParam("X-Amz-Security-Token", xmlToken.getChildContent("GetSessionTokenResult|Credentials|SessionToken"));

        StringBuilder sbResponse = new StringBuilder();
        try {
            rest.fullRequestNoBodySb("GET", "/", sbResponse);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int statusCode = rest.getResponseStatusCode();
        System.out.println("Response status code = " + statusCode);

        Xml xml = new Xml();
        xml.loadSb(sbResponse, true);
        System.out.println(xml.getXml());

        if (statusCode != 200) {
            System.out.println("Failed.  See error information in the XML.");
            return;
        }
    }
}