Fetch messages from API

You need your AfricasTalking username and APIKey for any request to our API. If you don't have an APIKey, please click here to get one

The Java code snippet below shows how to send airtime using our API.

The code uses our Java gateway class: AfricasTalkingGateway.java [ Download]

To help decode JSON responses, you will need to add one of the available JAVA libraries as a dependency. For this tutorial we chose to use json-20090211.jar which you can download from this repository.

Note On SSL Certificate Validation Issues

Some of our users have experienced SSL Certificate validation issues when connecting to our website due to our use of https. The error you see may look something like this:

Unable to find valid certification path to requested target

Please do not panic! Our certificate is perfectly valid (as evidenced by these verification tests), and the error you are seeing is quite common amongst Java clients connecting to secure websites. Here is how to fix the issue:

  • Download and compile InstallCert.java (you can find the code here).
  • On the CMD prompt(Windows) or Terminal(*nix), run: java InstallCert api.africastalking.com
    This will download a copy of our Certificate and create a file named jssecacerts in the current directory.
  • You can now add our Certificate to your trusted store by copying the created jssecacerts file to the Java security directory under $JAVA_HOME/jre/lib/security
// Make sure the downloaded jar file is in the classpath
import org.json.*;

public class TestReceiving
{
    public static void main(String[] args_)
    {
		// Specify your login credentials
		String username = "MyAfricasTalkingUsername";
		String apiKey   = "MyAfricasTalkingAPIKey";

		// Create a new instance of our awesome gateway class
		AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);

		/*************************************************************************************
			NOTE: If connecting to the sandbox:

			1. Use "sandbox" as the username
			2. Use the apiKey generated from your sandbox application
				https://account.africastalking.com/apps/sandbox/settings/key
			3. Add the "sandbox" flag to the constructor

			AfricasTalkingGateway gateway = new AfricasTalkingGateway(username, apiKey, "sandbox");
		**************************************************************************************/

		// Our gateway will return 10 messages at a time back to you, starting with
		// what you currently believe is the lastReceivedId. Specify 0 for the first
		// time you access the gateway, and the ID of the last message we sent you
		// on subsequent results
		int lastReceivedId = 0;
	
		// Here is a sample of how to fetch all messages using a while loop
		try {
			JSONArray results = null;
			do {
				results = gateway.fetchMessages(lastReceivedId);
				for(int i = 0; i < results.length(); ++ i) {
					JSONObject result = results.getJSONObject(i);
					System.out.println("From: " + result.getString("from"));
					System.out.println("To: " + result.getString("to"));
					System.out.println("Message: " + result.getString("text"));
					System.out.println("Date: " + result.getString("date"));
					System.out.println("linkId: " + result.getString("linkId"));
					lastReceivedId = result.getInt("id");
				}
			} while ( results.length() > 0 );
		} catch (Exception e) {
			System.out.println("Caught an Exception: " + e.getMessage());
	}
	// NOTE: Be sure to save lastReceivedId here for next time
	}
}

Parameter Location Description Required
API key Header API key generated from your account settings Yes
Accept Header This is the format you would like your data formatted. It may be application/xml or application/json. The default is application/xml. The gateway classes provided uses appliaction/json. No
username URL This is your username Yes
lastReceivedId URL This is the id of the message that you last processed. If this is your first call, pass in 0 Yes
XML
<?xml version="1.0"?>
  <AfricastalkingResponse>
    <SMSMessageData>
      <Messages>
        <from>+254711XXXYYY</from>
        <to>5252</to>
        <text>A test message</text>
        <linkId>messageLinkId</linkId>
        <date>2012-07-15 15:40:06</date>
        <id>1</id>
      </Message>
      .
      .
      .
      .
      <Message>
        <from>+254733YYYZZZ</from>
        <to>5252</to>
        <text>Another test message</text>
        <linkId>messageLinkId</linkId>
        <date>2012-07-15 15:47:06</date>
        <id>10</id>
      </Message>
    </Messages>
  </SMSMessageData>
</AfricastalkingResponse>
JSON

{"SMSMessageData":
  {"Messages":
    [
      {
        "from":"+254711XXXYYY",
        "to":"5252",
        "text":"A test message",
        "linkId": "messageLinkId",
        "date":"2012-07-15 15:40:06",
        "id":"1"
      },
      .
      .
      .
      .
      {
        "from":"+254733YYYZZZ",
        "to":"5252",
        "text":"Another test message",
        "linkId": "messageLinkId",
        "date":"2012-07-15 15:47:06",
        "id":"10"
      }
    ]
  }
}
Example using CURL client
curl -v -H "Accept: application/xml" -H "Apikey:fb752d3417021812f0961y6c9464832dd1adb1e555c73f1e7c32bcc006488674" https://api.africastalking.com/version1/messaging?username=myUsername&lastReceivedId=0 --insecure