Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Receive and Reply to Incoming Messages - Java


In this guide, we'll show you how to use Programmable Messaging(link takes you to an external page) to respond to incoming messages in your Java web application. When someone sends a text message to your Twilio number, Twilio can call a webhook you create in Java from which you can send a reply back using TwiML. All this talk of webhooks and TwiML got you feeling anxious? Fear not. This guide will help you master the basics in no time.

(information)

Info

Twilio can send your web application an HTTP request when certain events happen, such as an incoming text message to one of your Twilio phone numbers. These requests are called webhooks, or status callbacks. For more, check out our guide to Getting Started with Twilio Webhooks. Find other webhook pages, such as a security guide and an FAQ in the Webhooks section of the docs.

The code snippets in this guide are written using Java SDK 8 or higher, and make use of the following library:

Let's get started!

Incoming SMS Diagram.

What is a Webhook?

what-is-a-webhook page anchor

Webhooks are user-defined HTTP(link takes you to an external page) callbacks. They are usually triggered by some event, such as receiving an SMS message or an incoming phone call. When that event occurs, Twilio makes an HTTP request (usually a POST or a GET(link takes you to an external page)) to the URL configured for the webhook.

To handle a webhook, you only need to build a small web application that can accept the HTTP requests. Almost all server-side programming languages offer some framework for you to do this. Examples across languages include ASP.NET MVC(link takes you to an external page) for C#, Servlets(link takes you to an external page) and Spark(link takes you to an external page) for Java, Express(link takes you to an external page) for Node.js, Django(link takes you to an external page) and Flask(link takes you to an external page) for Python, and Rails(link takes you to an external page) and Sinatra(link takes you to an external page) for Ruby. PHP(link takes you to an external page) has its own web app framework built in, although frameworks like Laravel(link takes you to an external page), Symfony(link takes you to an external page) and Yii(link takes you to an external page) are also popular.

Whichever framework and language you choose, webhooks function the same for every Twilio application. They will make an HTTP request to a URI that you provide to Twilio. Your application performs whatever logic you feel necessary - read/write from a database, integrate with another API or perform some computation - then replies to Twilio with a TwiML response with the instructions you want Twilio to perform.

What is TwiML?

what-is-twiml page anchor

TwiML is the Twilio Markup Language, which is just to say that it's an XML(link takes you to an external page) document with special tags defined by Twilio to help you build your SMS and voice applications. TwiML is easier shown than explained. Here's some TwiML you might use to respond to an incoming phone call:


_10
<?xml version="1.0" encoding="UTF-8"?>
_10
<Response>
_10
<Say>Thanks for calling!</Say>
_10
</Response>

And here's some TwiML you might use to respond to an incoming SMS message:


_10
<?xml version="1.0" encoding="UTF-8"?>
_10
<Response>
_10
<Message>We got your message, thank you!</Message>
_10
</Response>

Every TwiML document will have the root <Response> element and within that can contain one or more verbs. Verbs are actions you'd like Twilio to take, such as <Say> a greeting to a caller, or send an SMS <Message> in reply to an incoming message. For a full reference on everything you can do with TwiML, refer to our TwiML API Reference.


Generating TwiML in your web application

generating-twiml-in-your-web-application page anchor

When someone sends a text message to your Twilio number, you can send a reply back using TwiML using your configured webhook(link takes you to an external page). Here's how to generate TwiML using the helper library.

Respond to an incoming text message

respond-to-an-incoming-text-message page anchor

When your Twilio phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server can reply with a text message using the Twilio helper library.

Java

_27
import com.twilio.twiml.MessagingResponse;
_27
import com.twilio.twiml.messaging.Body;
_27
import com.twilio.twiml.messaging.Message;
_27
_27
import static spark.Spark.*;
_27
_27
public class SmsApp {
_27
public static void main(String[] args) {
_27
get("/", (req, res) -> "Hello Web");
_27
_27
post("/sms", (req, res) -> {
_27
res.type("application/xml");
_27
Body body = new Body
_27
.Builder("The Robots are coming! Head for the hills!")
_27
.build();
_27
Message sms = new Message
_27
.Builder()
_27
.body(body)
_27
.build();
_27
MessagingResponse twiml = new MessagingResponse
_27
.Builder()
_27
.message(sms)
_27
.build();
_27
return twiml.toXml();
_27
});
_27
}
_27
}

When you use the helper library, you don't have to worry about generating the raw XML yourself. Of course, if you prefer to do that, then we won't stop you.

You have the code, now you need a URL you can give to Twilio. Twilio can only access public servers on the Internet. That means you need to take your web application and publish it to a web or cloud hosting provider (of which there are many(link takes you to an external page)), you can host it on your own server, or you can use a service such as ngrok(link takes you to an external page) to expose your local development machine to the internet. We generally only recommend the latter for development and testing purposes and not for production deployments.

Configure Your Webhook URL

configure-your-webhook-url page anchor

Now that you have a URL for your web application's TwiML reply generating routine, you can configure your Twilio phone number to call your webhook URL whenever a new media message comes in for you.

  1. Log into Twilio.com and go to the Console's Numbers page
  2. Click on the phone number you'd like to modify
  3. Find the Messaging section and the "A MESSAGE COMES IN" option
  4. Select "Webhook" and paste in the URL you want to use:
SMS Webhook.

Make sure you choose HTTP POST or HTTP GET to correspond to what your web application is expecting. Usually the default of POST will be fine.

You'll notice in the console that there is also a spot to provide a Webhook URL for when the "PRIMARY HANDLER FAILS." Twilio will call this URL in the event that your primary handler returns an error or does not return a response within 15 seconds. Refer to our Availability and Reliability guide for more details on the fallback URL.

(warning)

Warning

Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them.

Learn more about HTTP authentication here, and check out our full guide to securing your Servlet application by validating incoming Twilio requests.


Respond with media message

respond-with-media-message page anchor

To send a message including media (e.g. an image), simply add an image URL to your text message body. If necessary, restart your server, then text your Twilio number again. You should receive a text message that includes an image. You can even send multiple images by adding more Media elements to your response. Check out the API Reference for more details.

(information)

Info

MMS messages can only be sent and received by numbers having MMS capability. You can check the capabilities(link takes you to an external page) of numbers in the account portal or query the Available Phone Numbers resource to search for Twilio numbers that are MMS enabled.

Generate a TwiML Message with Image

generate-a-twiml-message-with-image page anchor
Java

_33
package com.twilio;
_33
import javax.servlet.http.HttpServlet;
_33
import javax.servlet.http.HttpServletRequest;
_33
import javax.servlet.http.HttpServletResponse;
_33
import java.io.IOException;
_33
_33
import com.twilio.twiml.messaging.Body;
_33
import com.twilio.twiml.messaging.Media;
_33
import com.twilio.twiml.messaging.Message;
_33
import com.twilio.twiml.MessagingResponse;
_33
import com.twilio.twiml.TwiMLException;
_33
_33
public class TwilioServlet extends HttpServlet {
_33
_33
// service() responds to both GET and POST requests.
_33
// You can also use doGet() or doPost()
_33
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
_33
Message sms = new Message.Builder()
_33
.body(new Body("The Robots are coming! Head for the hills!"))
_33
.media(new Media("https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg"))
_33
.build();
_33
_33
MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();
_33
_33
response.setContentType("application/xml");
_33
_33
try {
_33
response.getWriter().print(twiml.toXml());
_33
} catch (TwiMLException e) {
_33
e.printStackTrace();
_33
}
_33
}
_33
}


Custom responses to incoming media messages

custom-responses-to-incoming-media-messages page anchor

Let's take a look at how we might respond to an incoming message with a different message depending on the incoming Body parameter from the incoming Twilio Request.

Generate a dynamic TwiML Message

generate-a-dynamic-twiml-message page anchor
Java

_37
import java.io.IOException;
_37
_37
import javax.servlet.http.HttpServlet;
_37
import javax.servlet.http.HttpServletRequest;
_37
import javax.servlet.http.HttpServletResponse;
_37
_37
import com.twilio.twiml.messaging.Body;
_37
import com.twilio.twiml.messaging.Message;
_37
import com.twilio.twiml.MessagingResponse;
_37
import com.twilio.twiml.TwiMLException;
_37
_37
public class TwilioServlet extends HttpServlet {
_37
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
_37
String body = request.getParameter("Body");
_37
String message = "Message";
_37
if (body.equals("hello")) {
_37
// Say hi
_37
message = "Hi there!";
_37
} else if (body.equals("bye")) {
_37
// Say goodbye
_37
message = "Goodbye!";
_37
}
_37
_37
// Create a TwiML response and add our friendly message.
_37
Body messageBody = new Body.Builder(message).build();
_37
Message sms = new Message.Builder().body(messageBody).build();
_37
MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();
_37
_37
response.setContentType("application/xml");
_37
_37
try {
_37
response.getWriter().print(twiml.toXml());
_37
} catch (TwiMLException e) {
_37
e.printStackTrace();
_37
}
_37
}
_37
}

Now, try sending your Twilio number a text that says "hi" or "bye", and you should get the corresponding response.


Receive incoming messages without sending a reply

receive-incoming-messages-without-sending-a-reply page anchor

If you would like to receive incoming messages but not send an outgoing reply message, you can return an empty TwiML response. Twilio still expects to receive TwiML in response to its request to your server, but if the TwiML does not contain any directions, Twilio will accept the empty TwiML without taking any actions.

Receive an incoming message without sending a response

receive-an-incoming-message-without-sending-a-response page anchor
Java

_17
import com.twilio.twiml.MessagingResponse;
_17
import com.twilio.twiml.messaging.Body;
_17
import com.twilio.twiml.messaging.Message;
_17
_17
import static spark.Spark.*;
_17
_17
public class SmsApp {
_17
public static void main(String[] args) {
_17
get("/", (req, res) -> "Hello Web");
_17
_17
post("/sms", (req, res) -> {
_17
res.type("application/xml");
_17
MessagingResponse twiml = new MessagingResponse.Builder().build();
_17
return twiml.toXml();
_17
});
_17
}
_17
}


Enhance messages with add-ons

enhance-messages-with-add-ons page anchor

Need more information about the phone number that sent the message? Need to analyze the message itself for sentiment or other data? Add-ons are available in the Add-ons Marketplace(link takes you to an external page) to accomplish these tasks and more.

To learn how to enable Add-ons for your incoming SMS messages, refer to our Add-ons quickstart.

Add-ons Diagram.

When you're ready to dig deeper into handling incoming messages, check out our guide on how to Create an SMS Conversation and our Automated Survey(link takes you to an external page) tutorial.


Rate this page: