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.

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.

Double check that the region is correct on your base URL. Learn more about regional options here.

Set up an 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

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.