This topic describes how to use the Java sample code to receive messages.

public class ConsumerDemo {

    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");

        //this client need only initialize once
        MNSClient client = account.getMNSClient(); 

        // Receive 10 messages from a queue. 
        try{
            CloudQueue queue = client.getQueueRef("TestQueue");
            for (int i = 0; i < 10; i++)
            {
                Message popMsg = queue.popMessage();
                if (popMsg ! = null){
                    System.out.println("message handle: " + popMsg.getReceiptHandle());
                    // Base64 decoding is performed by default. 
                    System.out.println("message body: " + popMsg.getMessageBodyAsString());
                    // The original message content that is not decoded.
                    // System.out.println("message body: " + popMsg.getMessageBodyAsRawString ());
                    System.out.println("message id: " + popMsg.getMessageId());
                    System.out.println("message dequeue count:" + popMsg.getDequeueCount());

                    // Delete received messages.
                    queue.deleteMessage(popMsg.getReceiptHandle());
                    System.out.println("delete message successfully.\n");
                }
                else{
                    System.out.println("message not exist in TestQueue.\n");
                }
            }
        } catch (ClientException e) {
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availablity.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            e.printStackTrace();
            logger.error("MNS exception requestId:" + se.getRequestId(), se);
            if (se.getErrorCode() ! = null) {
                if (se.getErrorCode().equals("QueueNotExist"))
                {
                    System.out.println("Queue is not exist.Please create before use");
                } else if (se.getErrorCode().equals("TimeExpired"))
                {
                    System.out.println("The request is time expired. Please check your local machine timeclock");
                }
            /*
            you can get more MNS service error code from following link:
            https://www.alibabacloud.com/help/doc-detail/27501.htm
            */
            }
        }catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();
    }
}