How to Send and Receive SMS Messages in Java Using Plivo’s SMS API

How to Send and Receive SMS Messages in Java Using Plivo’s SMS API

Your company has settled on Plivo to handle its voice and messaging communications, and now it’s your job to start integrating Plivo into your company’s applications. Don’t worry — Plivo has a Java SDK to help you out. You can use it write Java applications that send and receive SMS messages.

In this guide, we’ll explain how to send and receive SMS messages in Java. We'll walk you through the process of setting up your account, writing code snippets for sending messages and receiving responses through our SMS API. By the end, you'll be ready to leverage SMS communication for notifications, alerts, or even two-way interactions in Java.

Prerequisites

Before we walk you through the steps to send SMS in Java, you’ll need a few prerequisites in place: 

To make sure you’re ready to go, refer to our guide Set up your Java Dev Environment for Messaging. This guide will go into more detail to help you set up a development environment to trigger API requests in Java. The entire process takes around five minutes.

{{cta-style-1}}

Send an SMS in Java

Now you’re ready to start. Create a Java class in the project called SendSMS and paste into it this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.io.IOException;
import java.util.Collections;
import com.plivo.api.Plivo;
import com.plivo.api.exceptions.PlivoRestException;
import com.plivo.api.models.message.Message;
import com.plivo.api.models.message.MessageCreateResponse;

class SendSMS
{
    public static void main(String [] args) throws IOException, PlivoRestException {
        Plivo.init("<auth_id>","<auth_token>");
        MessageCreateResponse response = Message.creator("<sender_id>",
                "<destination_number>",
                "Hello, from Java!")
                .create();
        System.out.println(response);
    }
}

Replace the auth placeholders with actual values from the Plivo console. Replace the phone number placeholders with actual phone numbers in E.164 format (for example, +12025551234). In countries other than the US and Canada you can use a sender ID for the message source. You must have a Plivo phone number to send messages to the US or Canada; you can rent a Plivo number from Phone Numbers > Buy Numbers on the Plivo console or via the Numbers API. Save the file and run it.

Note: If you’re using a Plivo Trial account, you can send messages only to phone numbers that have been verified with Plivo. You can verify (sandbox) a number by going to the console’s Phone Numbers > Sandbox Numbers page.

Receive an SMS in Java

Of course sending messages is only half of the equation. Plivo supports receiving SMS text messages in many countries (see our SMS API coverage page and click on the countries you’re interested in). When someone sends an SMS message to a Plivo phone number, you can receive it on your server by using a Spark web app. Install Spark by editing pom.xml and adding dependencies for Spark and the Simple Logging Facade for Java (SLF4J), which you’ll also want.

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.21</version>
</dependency>

Then create a Java class in the project called ReceiveSMS and paste into it this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import static spark.Spark.*;

public class ReceiveSms {
    public static void main(String[] args) {
        get("/receive_sms", (request, response) -> {
            // Sender's phone number
            String from_number = request.queryParams("From");
            // Receiver's phone number - Plivo number
            String to_number = request.queryParams("To");
            // The text that was received
            String text = request.queryParams("Text");
            // Print the message
            System.out.println(from_number + " " + to_number + " " + text);
            return "Message Received";
        });
    }
}

When you run the project you should see your basic server app in action on http://localhost:4567/receive_sms.

That’s fine for testing, but it’s not much good if you can’t connect to the internet to receive incoming messages and handle callbacks. For that, we recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels. Install it and run ngrok on the command line, specifying the port that hosts the application on which you want to receive messages:

./ngrok http [portnum]

Ngrok will display a forwarding link that you can use as a webhook to access your local server using the public network.

Sample ngrok CLI

Now you can create an application to receive SMS messages (follow our Quickstart guide for details). You can also create a Java class to reply to incoming SMS messages.

Why you should use Java to send and receive SMS

Java’s platform independence, ease of use, and security make it a great programming language for sending and receiving SMS messages. Compared to other programming languages, Java is simple to use and easy to understand. 

Java is also an object-oriented programming language, meaning developers can easily reuse objects in other programs. Because it’s platform independent (e.g., Write Once Run Anywhere, or WORA), Java SMS applications can run on various platforms (Windows, macOS, Linux, etc.) without modification.

Finally, Java provides robust security mechanisms to protect sensitive SMS data. SSL/TLS support for SMS transactions makes secure communication channels easy to establish.

Get started with Plivo to send SMS in Java

That’s all there is to sending and receiving SMS messages using Plivo’s Java SDK. 

Don’t use Java? Don’t worry — we have SDKs for PHP, Python, Node.js, Ruby, .NET Core, .NET Framework, and Go.

Haven’t tried Plivo yet? Getting started is easy and takes only five minutes. Sign up today.

Get Volume Pricing

Thousands of businesses in more than 220 countries trust Plivo’s cloud communications platform

The best communications platform forthe world’s leading entertainment service

Frequently asked questions

No items found.
footer bg

Subscribe to Our Newsletter

Get monthly product and feature updates, the latest industry news, and more!

Thank you icon
Thank you!
Thank you for subscribing
Oops! Something went wrong while submitting the form.