Receive an SMS Message with Java

Note:

Before you can get started, you need the following already set up:

Handle and reply to incoming SMS Messages to your Sinch number.

When someone sends an SMS message to your Sinch number, we will send an http request to your server. This is known as a callback or webhook. You can configure your webhooks in your SMS API settings.

Learn how to quickly set up a Java server to receive SMS messages with the Sinch API using the Spark web application framework.

Steps:
  1. Install the Sinch Java library
  2. Configure your callback URL
  3. Send your SMS message

Install the Sinch SDK for Java

  1. If you don't have a java project already, create one:
    Copy
    Copied
    gradle init
  2. Select your application, and then accept all default values.

Add Gradle dependencies

To listen to incoming HTTP requests, we will use Spark.

In your build.gradle file add the following three dependencies:

Copy
Copied
dependencies {
  implementation 'com.sinch:sdk-sms:1.0.+'
  implementation group: "com.sparkjava", name: "spark-core", version: "2.9.3"
  implementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.31'
}

Update the App.java file

When you have installed the SDK and have a Java project you are ready to write some code.

Change your App.java to the supplied code.

Receive an SMS message

// Find your servicePlanId and Token at https://dashboard.sinch.com/sms/api/rest
// Install the Java helper library at https://developers.sinch.com/docs/sms/sdks/java/
// Find your Sinch virtual number at // https://dashboard.sinch.com/numbers/your-numbers

import com.sinch.xms.*;
import com.sinch.xms.api.*;

import static spark.Spark.*;

public class App {
	private static final String SERVICE_PLAN_ID = "YOUR_servicePlanId";
	private static final String TOKEN = "YOUR_API_token";
	private static ApiConnection conn;
    private static ApiObjectMapper mapper = new ApiObjectMapper();

	public static void main(String[] args) {
       
        conn = ApiConnection
                .builder()
                .servicePlanId(SERVICE_PLAN_ID)
                .token(TOKEN)
                .start();
        get("/", (req, res) -> "The server is up and running");
      
        post("/", (request, response) -> {
            MoTextSms message = mapper.readValue(request.body(), MoTextSms.class);
            String[] RECIPIENTS = { message.sender() };
            String SENDER = message.recipient();
            MtBatchTextSmsCreate reply = SinchSMSApi
                                            .batchTextSms()
                                            .sender(SENDER)
                                            .addRecipient(RECIPIENTS)
                    						.body("You sent: " + message.body())
											.build();
                try {
                // if there is something wrong with the batch
                // it will be exposed in APIError
                MtBatchTextSmsResult batch = conn.createBatch(reply);
                System.out.println(batch.id());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println("incoming message:" + message);
            return "incoming message:" + message;
        });
	}
}

Fill in your parameters

Change the following parameters in the code to your values:

ParameterYour value
SERVICE_PLAN_IDThe service plan ID found on your Sinch Customer Dashboard.
TOKENThe API token found on your Sinch Customer Dashboard. Click Show to reveal your API token.

Set up a ngrok tunnel and run your application

  1. In the terminal or command prompt window, start running your application with:
    Copy
    Copied
    gradle run
  2. Before you can handle incoming traffic to your local server, open up a tunnel to your local server. For that, you can use an ngrok tunnel. If you haven't already, install ngrok, and then open a terminal or command prompt. Take note of the URL that ends in .ngrok.io.
    Copy
    Copied
    ngrok http 4567

Configure your Callback URL

You need to configure a Callback URL for your Sinch account. Login to your Sinch Customer Dashboard. Click on the service plan ID link and edit the Callback URL field with the ngrok.io domain URL from the previous step.

Send your SMS message

Now send an SMS message to your Sinch number from your mobile phone and you will get an automatic reply.

Next Steps

Was this page helpful?

Receive an SMS message

// Find your servicePlanId and Token at https://dashboard.sinch.com/sms/api/rest
// Install the Java helper library at https://developers.sinch.com/docs/sms/sdks/java/
// Find your Sinch virtual number at // https://dashboard.sinch.com/numbers/your-numbers

import com.sinch.xms.*;
import com.sinch.xms.api.*;

import static spark.Spark.*;

public class App {
	private static final String SERVICE_PLAN_ID = "YOUR_servicePlanId";
	private static final String TOKEN = "YOUR_API_token";
	private static ApiConnection conn;
    private static ApiObjectMapper mapper = new ApiObjectMapper();

	public static void main(String[] args) {
       
        conn = ApiConnection
                .builder()
                .servicePlanId(SERVICE_PLAN_ID)
                .token(TOKEN)
                .start();
        get("/", (req, res) -> "The server is up and running");
      
        post("/", (request, response) -> {
            MoTextSms message = mapper.readValue(request.body(), MoTextSms.class);
            String[] RECIPIENTS = { message.sender() };
            String SENDER = message.recipient();
            MtBatchTextSmsCreate reply = SinchSMSApi
                                            .batchTextSms()
                                            .sender(SENDER)
                                            .addRecipient(RECIPIENTS)
                    						.body("You sent: " + message.body())
											.build();
                try {
                // if there is something wrong with the batch
                // it will be exposed in APIError
                MtBatchTextSmsResult batch = conn.createBatch(reply);
                System.out.println(batch.id());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println("incoming message:" + message);
            return "incoming message:" + message;
        });
	}
}