In this guide, we'll show you how to use Programmable Messaging 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.
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!
Webhooks are user-defined HTTP 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
) 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 for C#, Servlets and Spark for Java, Express for Node.js, Django and Flask for Python, and Rails and Sinatra for Ruby. PHP has its own web app framework built in, although frameworks like Laravel, Symfony and Yii 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.
TwiML is the Twilio Markup Language, which is just to say that it's an XML 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:
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Say>Thanks for calling!</Say>4</Response>
And here's some TwiML you might use to respond to an incoming SMS message:
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Message>We got your message, thank you!</Message>4</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.
When someone sends a text message to your Twilio number, you can send a reply back using TwiML using your configured webhook. Here's how to generate TwiML using the helper library.
1import com.twilio.twiml.MessagingResponse;2import com.twilio.twiml.messaging.Body;3import com.twilio.twiml.messaging.Message;45import static spark.Spark.*;67public class SmsApp {8public static void main(String[] args) {9get("/", (req, res) -> "Hello Web");1011post("/sms", (req, res) -> {12res.type("application/xml");13Body body = new Body14.Builder("The Robots are coming! Head for the hills!")15.build();16Message sms = new Message17.Builder()18.body(body)19.build();20MessagingResponse twiml = new MessagingResponse21.Builder()22.message(sms)23.build();24return twiml.toXml();25});26}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), you can host it on your own server, or you can use a service such as ngrok 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.
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.
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.
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.
To send a message including media (e.g. an image), 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.
MMS messages can only be sent and received by numbers having MMS capability. You can check the capabilities of numbers in the account portal or query the Available Phone Numbers resource to search for Twilio numbers that are MMS enabled.
1package com.twilio;2import javax.servlet.http.HttpServlet;3import javax.servlet.http.HttpServletRequest;4import javax.servlet.http.HttpServletResponse;5import java.io.IOException;67import com.twilio.twiml.messaging.Body;8import com.twilio.twiml.messaging.Media;9import com.twilio.twiml.messaging.Message;10import com.twilio.twiml.MessagingResponse;11import com.twilio.twiml.TwiMLException;1213public class TwilioServlet extends HttpServlet {1415// service() responds to both GET and POST requests.16// You can also use doGet() or doPost()17public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {18Message sms = new Message.Builder()19.body(new Body("The Robots are coming! Head for the hills!"))20.media(new Media("https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg"))21.build();2223MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();2425response.setContentType("application/xml");2627try {28response.getWriter().print(twiml.toXml());29} catch (TwiMLException e) {30e.printStackTrace();31}32}33}
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.
1import java.io.IOException;23import javax.servlet.http.HttpServlet;4import javax.servlet.http.HttpServletRequest;5import javax.servlet.http.HttpServletResponse;67import com.twilio.twiml.messaging.Body;8import com.twilio.twiml.messaging.Message;9import com.twilio.twiml.MessagingResponse;10import com.twilio.twiml.TwiMLException;1112public class TwilioServlet extends HttpServlet {13public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {14String body = request.getParameter("Body");15String message = "Message";16if (body.equals("hello")) {17// Say hi18message = "Hi there!";19} else if (body.equals("bye")) {20// Say goodbye21message = "Goodbye!";22}2324// Create a TwiML response and add our friendly message.25Body messageBody = new Body.Builder(message).build();26Message sms = new Message.Builder().body(messageBody).build();27MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();2829response.setContentType("application/xml");3031try {32response.getWriter().print(twiml.toXml());33} catch (TwiMLException e) {34e.printStackTrace();35}36}37}
Now, try sending your Twilio number a text that says "hi" or "bye", and you should get the corresponding response.
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.
1import com.twilio.twiml.MessagingResponse;2import com.twilio.twiml.messaging.Body;3import com.twilio.twiml.messaging.Message;45import static spark.Spark.*;67public class SmsApp {8public static void main(String[] args) {9get("/", (req, res) -> "Hello Web");1011post("/sms", (req, res) -> {12res.type("application/xml");13MessagingResponse twiml = new MessagingResponse.Builder().build();14return twiml.toXml();15});16}17}
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 Twilio Marketplace to accomplish these tasks and more.
To learn how to enable Add-ons for your incoming SMS messages](https://console.twilio.com/us1/develop/add-ons/catalog?products=programmable_messaging), refer to our Add-ons tutorial. To learn how to enable Add-ons for your incoming SMS messages, see the How to Use Twilio Marketplace Add-on Listings guide.
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 tutorial.