Receive an SMS Message with Java
Note:
Before you can get started, you need the following already set up:
- Set all SMS API configuration settings.
- JDK 11 or later and a familiarity with how to create a new Java application.
- Gradle and a familiarity with how use the Gradle build tools.
- ngrok. You'll use ngrok to open a tunnel to your local server.
Handle and reply to incoming SMS Messages to your Sinch number.
When someone sends an SMS message to your Sinch number, we will send anhttp
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.
Install the Sinch SDK for Java
- If you don't have a java project already, create one:
gradle init
- Select your application, and then accept all default values.
Add Gradle dependencies
To listen to incoming HTTP requests, we will use Spark.
In yourbuild.gradle
file add the following three dependencies: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 yourApp.java
to the supplied code.Fill in your parameters
Change the following parameters in the code to your values:
Parameter | Your value |
---|---|
SERVICE_PLAN_ID | The service plan ID found on your Sinch Customer Dashboard. |
TOKEN | The 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
- In the terminal or command prompt window, start running your application with:
gradle run
- 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
.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 section.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
- Explore the API specification to test more endpoints.