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

Amazon SQS: List Queues with Pagination

See more Amazon SQS Examples

List queues owned by the current account in the chosen region. Set MaxResults to receive NextToken and follow all pages, with an optional case-sensitive QueueNamePrefix. Empty pages are processed correctly and do not override a continuation token. A Hashtable rejects repeated tokens; a page bound reports incomplete enumeration.

Returns queue URLs, not queue ARNs or message contents. Save the selected URL for queue-specific requests, or use GetQueueUrl when the name is already known. ListQueues does not enumerate another account through cross-account permissions. A changing queue collection is not an atomic snapshot.

Uses SQS's AWS JSON protocol: POST to the regional root / with Content-Type: application/x-amz-json-1.0 and an operation-specific X-Amz-Target: AmazonSQS.... Chilkat.Rest and AuthAws sign with AWS Signature Version 4, service sqs. AWS still supports the older Query/XML protocol; these examples use JSON for simpler request and response handling. No AWS SDK is required.

Provide current IAM credentials in a private qa_data/aws/sqs.json with string fields access_key, secret_key, and session_token for temporary credentials. Queue-specific examples also read queue_url from this file. Set the region in the code to match the queue. These examples use commercial regional endpoints; other partitions or custom endpoints require corresponding changes. Prefer short-lived role credentials. The file is explicitly loaded; profiles and credential refresh are not automatic. Keep it outside public content and source control. The temporary token is included in the signed query; keep URLs and diagnostics private. TLS certificate verification is enabled.

Transport completion, HTTP status, and response validity are checked separately. Use bounded backoff with jitter for retryable errors, and refresh expired credentials. A timed-out write or receive may already have been accepted. Standard queues can deliver duplicates: make application processing idempotent and delete only after successful processing. Automatic reconnection is disabled for writes and receives to avoid replay after a lost response. Read-only queue listing permits reconnection.

Required IAM action: sqs:ListQueues. ListQueues requires Resource *.

AWS ListQueues reference

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // StringBuilder compares text by value in every generated language.
        StringBuilder textCompare = new StringBuilder();
        // 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 SQS operation.
        JsonObject credentials = new JsonObject();
        credentials.setStrict(true);
        try {
            credentials.loadFile("qa_data/aws/sqs.json");
        } catch (ChilkatException e) {
            System.out.println("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) || (sameText1)) {
            System.out.println("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) || (sameText2)) {
            System.out.println("Missing or invalid secret_key.");
            return;
        }

        // Set this once to the region containing the queue.
        String region = "us-west-2";
        StringBuilder endpoint = new StringBuilder();
        try {
            endpoint.append("sqs.");

            endpoint.append(region);

            endpoint.append(".amazonaws.com");
        } catch (ChilkatException e) {
            System.out.println("Could not prepare the request.");
            return;
        }

        AuthAws aws = new AuthAws();
        aws.setAccessKey(credentials.stringOf("access_key"));
        aws.setSecretKey(credentials.stringOf("secret_key"));
        aws.setRegion(region);
        aws.setServiceName("sqs");
        aws.setSignatureVersion(4);
        Rest rest = new Rest();
        rest.setConnectTimeoutMs(20000);
        rest.setIdleTimeoutMs(60000);
        try {
            rest.setAuthAws(aws);
        } catch (ChilkatException e) {
            System.out.println("Could not configure AWS signing.");
            return;
        }

        // Temporary IAM/STS credentials require their session token on every signed request.
        // AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
        // Leave session_token absent or empty only for credentials that do not have one.
        if (credentials.hasMember("session_token")) {
            if (credentials.jsonTypeOf("session_token") != 1) {
                System.out.println("session_token must be a string.");
                return;
            }

            textCompare.clear();
            textCompare.setString(credentials.stringOf("session_token"));
            boolean sameText3 = textCompare.contentsEqual("", true);
            if (!sameText3) {
                try {
                    rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
                } catch (ChilkatException e) {
                    System.out.println("Could not set the session-token parameter.");
                    return;
                }
            }
        }

        // Supply a Socket to explicitly enable TLS certificate verification.
        Socket connection = new Socket();
        connection.setRequireSslCertVerify(true);
        connection.setMaxReadIdleMs(60000);
        connection.setMaxSendIdleMs(60000);
        try {
            connection.connect(endpoint.getAsString(), 443, true, 20000);
        } catch (ChilkatException e) {
            System.out.println("TLS connection failed; inspect diagnostics privately.");
            return;
        }

        try {
            rest.useConnection(connection, true);
        } catch (ChilkatException e) {
            System.out.println("Could not attach the TLS connection.");
            return;
        }

        try {
            rest.addHeader("Content-Type", "application/x-amz-json-1.0");
        } catch (ChilkatException e) {
            System.out.println("Could not set the content type.");
            return;
        }

        JsonObject body = new JsonObject();
        JsonObject result = new JsonObject();
        result.setStrict(true);
        StringBuilder requestBody = new StringBuilder();
        StringBuilder responseBody = new StringBuilder();
        try {
            rest.addHeader("X-Amz-Target", "AmazonSQS.ListQueues");

            body.updateInt("MaxResults", 1000);
        } catch (ChilkatException e) {
            System.out.println("Could not prepare the request.");
            return;
        }

        // Optional, case-sensitive queue-name prefix. Empty means no filter.
        String queueNamePrefix = "";
        textCompare.clear();
        textCompare.setString(queueNamePrefix);
        boolean sameText4 = textCompare.contentsEqual("", true);
        if (!sameText4) {
            try {
                body.updateString("QueueNamePrefix", queueNamePrefix);
            } catch (ChilkatException e) {
                System.out.println("Could not prepare the request.");
                return;
            }
        }

        Hashtable seenTokens = new Hashtable();
        int page = 0;
        boolean more = true;
        while (more) {
            if (page == 1000) {
                System.out.println("Stopped at 1000 pages; enumeration is incomplete. Save NextToken privately to resume.");
                return;
            }

            // EmitSb appends, so clear both builders before each request/page.
            requestBody.clear();
            responseBody.clear();
            try {
                body.emitSb(requestBody);
            } catch (ChilkatException e) {
                System.out.println("Could not serialize JSON.");
                return;
            }

            try {
                rest.fullRequestSb("POST", "/", requestBody, responseBody);
            } catch (ChilkatException e) {
                System.out.println("Request did not complete; inspect diagnostics privately.");
                // A write or receive may have reached SQS. Do not blindly replay it.
                return;
            }

            if (rest.getResponseStatusCode() != 200) {
                System.out.println("SQS HTTP status: " + rest.getResponseStatusCode());
                System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
                try {
                    result.loadSb(responseBody);
                    success = true;
                } catch (ChilkatException e) {
                    success = false;
                }
                if ((success) && (result.jsonTypeOf("__type") == 1)) {
                    System.out.println("AWS error type: " + result.stringOf("__type"));
                } else {
                    System.out.println("AWS error type: " + rest.responseHdrByName("x-amzn-errortype"));
                }

                // Error messages, payloads, receipt handles and signed URLs can be private.
                // HTTP 400 can be throttling, expired credentials, or invalid parameters.
                return;
            }

            try {
                responseBody.trim();
            } catch (ChilkatException e) {
                System.out.println("Could not inspect response.");
                return;
            }

            if (!responseBody.startsWith("{", true)) {
                System.out.println("Expected a JSON object response.");
                return;
            }

            try {
                result.loadSb(responseBody);
            } catch (ChilkatException e) {
                System.out.println("Expected well-formed JSON.");
                return;
            }

            int urlsType = result.jsonTypeOf("QueueUrls");
            if ((urlsType != -1) && (urlsType != 6)) {
                if (urlsType != 4) {
                    System.out.println("Expected QueueUrls array.");
                    return;
                }

                int i = 0;
                while (i < result.sizeOfArray("QueueUrls")) {
                    result.setI(i);
                    textCompare.clear();
                    textCompare.setString(result.stringOf("QueueUrls[i]"));
                    boolean sameText5 = textCompare.contentsEqual("", true);
                    if ((result.jsonTypeOf("QueueUrls[i]") != 1) || (sameText5)) {
                        System.out.println("Missing or invalid QueueUrls[i].");
                        return;
                    }

                    System.out.println("Queue URL: " + result.stringOf("QueueUrls[i]"));
                    i = i + 1;
                }
            }

            int tokenType = result.jsonTypeOf("NextToken");
            if ((tokenType == -1) || (tokenType == 6)) {
                more = false;
            } else {
                if (tokenType != 1) {
                    System.out.println("Expected a string NextToken.");
                    return;
                }

                String nextToken = result.stringOf("NextToken");
                textCompare.clear();
                textCompare.setString(nextToken);
                boolean sameText6 = textCompare.contentsEqual("", true);
                if (sameText6) {
                    more = false;
                } else {
                    if (seenTokens.contains(nextToken)) {
                        System.out.println("Repeated NextToken; enumeration is incomplete.");
                        return;
                    }

                    try {
                        seenTokens.addInt(nextToken, 1);
                    } catch (ChilkatException e) {
                        System.out.println("Could not record pagination token.");
                        return;
                    }

                    try {
                        body.updateString("NextToken", nextToken);
                    } catch (ChilkatException e) {
                        System.out.println("Could not prepare the request.");
                        return;
                    }
                }
            }

            page = page + 1;
        }

        System.out.println("Queue enumeration complete.");
    }
}