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

Programmable Voice Quickstart for Java


Ready to start sending and receiving phone calls with Twilio Programmable Voice using Java?

This Programmable Voice Quickstart for Java will teach you how to do this using the Twilio Java helper library for our REST API.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first voice-enabled Twilio phone number
  2. Set up your development environment to make and receive phone calls
  3. Make your first phone call with Twilio!
  4. Receive and respond to an inbound phone call which reads a message to the caller using Text to Speech

Prefer to get started by watching a video? Check out our Java Voice Quickstart video on Youtube(link takes you to an external page).


Sign up for Twilio and get a Twilio phone number

sign-up-for-twilio-and-get-a-twilio-phone-number page anchor
(information)

Info

If you already have a Twilio account and a voice-enabled Twilio phone number, you're all set here! Feel free to jump to the next step.

Before you can make a phone call from Java, you'll need to sign up for a Twilio account(link takes you to an external page) or sign into your existing account and purchase a voice-capable phone number(link takes you to an external page).

If you don't currently own a Twilio phone number with voice functionality, you'll need to purchase one. After navigating to the Buy a Number(link takes you to an external page) page, check the "Voice" box and click "Search."

Search for a voice-enabled phone number.

You'll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click "Buy" to add it to your account.

Purchase a voice-enabled phone number from Twilio.

Now that you have a Twilio account and a programmable phone number, you can start writing some code! To make things even easier, we'll set up our Java environment and then download Twilio's official helper library for Java applications.


Set up your Java environment

set-up-your-java-environment page anchor
(information)

Info

Already have your Java development environment all set up, and have a Twilio Java Helper library configured in your classpath? Feel free to skip the next two sections, and get right into making your first phone call with Twilio!

To make your first phone call, you'll need to have the Java Standard Edition (SE) Development Kit (JDK) installed - if you don't know if you have the JDK installed, run the following command to see what version you have:


_10
javac -version

You should see something similar to this output:


_10
javac 1.8.0_92

The Twilio SDK requires Java SE 8 or higher, which will appear as version number "1.8" or above when you run the above command.

If you have an older version of Java or no JDK at all, you'll need to install the JDK before going any further. Follow the directions for installing the Java SE Development Kit for your platform (Windows, Mac, Linux) from the Java SE Download Page(link takes you to an external page).


Download the standalone Twilio Java helper library

download-the-standalone-twilio-java-helper-library page anchor

Got Java all set up and ready to go? Fantastic!

Next, download the standalone Twilio Java Helper Library(link takes you to an external page). With that library, you'll have Java classes that help you call out to Twilio API's using Java, along with all the other dependencies you'll need to get going. When you download the jar file, download the one with a name similar to twilio-8.x-jar-with-dependencies.jar.

Prefer to use Maven, Gradle, or another build tool?

With Maven, place the following within your <dependencies> tag in your pom.xml file:


_10
<dependency>
_10
<groupId>com.twilio.sdk</groupId>
_10
<artifactId>twilio</artifactId>
_10
<version>8.0.0</version>
_10
</dependency>

With Gradle, paste the next line inside the dependencies block of your build.gradle file:


_10
compile group: "com.twilio.sdk", name: "twilio", version: "8.0.+"

If you are using a Java IDE to build your application, you can specify the group id, artifact id, and version number for your dependencies.

Regardless of the package manager you are using, remember to specify the latest version of the Twilio Java Helper Library - find the latest version number on the Twilio Java Helper Library(link takes you to an external page) page.

(warning)

Warning

This Twilio Java helper library is not meant for use in Android applications! Use this library for servers, command line applications, and similar projects. Shipping your Twilio Account SID and Auth Token to end users is a security risk for your Twilio account.

If you want to make or receive phone calls from a mobile application (Android or iOS), you should use the Twilio Programmable Voice SDK. Check out that page for directions on how to get started!


Make a phone call with Java

make-a-phone-call-with-java page anchor

Now that we have the JDK setup and the Twilio Java Helper library downloaded, we can make a phone call from the Twilio phone number we just purchased with a single API request. Create and open a new file called MakePhoneCall.java and type or paste in this code sample.

Make Phone Call using Twilio

make-phone-call-using-twilio page anchor
Java

_26
// Install the Java helper library from twilio.com/docs/libraries/java
_26
import java.net.URI;
_26
import java.net.URISyntaxException;
_26
_26
import com.twilio.Twilio;
_26
import com.twilio.rest.api.v2010.account.Call;
_26
import com.twilio.type.PhoneNumber;
_26
_26
public class MakePhoneCall {
_26
// Get your Account SID and Auth Token from https://twilio.com/console
_26
// To set up environment variables, see http://twil.io/secure
_26
public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
_26
public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
_26
_26
public static void main(String[] args) throws URISyntaxException {
_26
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
_26
_26
String from = "+15017122661";
_26
String to = "+14155551212";
_26
_26
Call call = Call.creator(new PhoneNumber(to), new PhoneNumber(from),
_26
new URI("http://demo.twilio.com/docs/voice.xml")).create();
_26
_26
System.out.println(call.getSid());
_26
}
_26
}

You'll need to edit this file a little more before your phone call will work:

Replace the placeholder credential values

replace-the-placeholder-credential-values page anchor

Swap the placeholder values for ACCOUNT_SID and AUTH_TOKEN with your personal Twilio credentials. Go to https://www.twilio.com/console(link takes you to an external page) and log in. On this page, you'll find your unique Account SID and Auth Token, which you'll need any time you make phone calls with the Twilio Java Helper Library. You can reveal your auth token by clicking on the eyeball icon:

Open MakePhoneCall.java and replace the values for ACCOUNT_SID and AUTH_TOKEN with your unique values.

(error)

Danger

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables(link takes you to an external page) for more information.

Replace the "from" phone number

replace-the-from-phone-number page anchor

Remember that voice-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the "to" phone number

replace-the-to-phone-number page anchor

Replace the to phone number with your phone number. This can be any phone number, but it's a good idea to test with your own phone so you can see the magic happen! As above, you should use E.164 formatting for this value.

Save your changes and compile this Java class from your terminal:


_10
javac -cp twilio-8.0.0-jar-with-dependencies.jar MakePhoneCall.java

We need to include that Twilio jar with the dependencies to compile our class from the command line. If you are using an Integrated Development Environment (IDE) such as IntelliJ IDEA, Netbeans or Eclipse, you can simply add that Twilio jar to your classpath or your project libraries like any other dependency. You can also use a build tool like Maven or Gradle to build and run your Java application - just specify Twilio's helper library as a dependency.

Once you have the Java class built, you will need to run it - if you are running it from the command line on macOS or Linux, the command will look like this:


_10
java -cp .:twilio-8.0.0-jar-with-dependencies.jar MakePhoneCall

On Windows, the equivalent command looks like this:


_10
java -cp .;twilio-8.0.0-jar-with-dependencies.jar MakePhoneCall

The difference is that on Windows, the Java classpath separator on the command line is a semicolon, and on macOS or Linux, it is a colon.

That's it! In a few moments, you should receive a phone call from your Twilio number on your phone.

(warning)

Warning

If you are on a Twilio Trial account, your outgoing voice calls are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs(link takes you to an external page).


Receive and reply to inbound phone calls

receive-and-reply-to-inbound-phone-calls page anchor

When your Twilio number receives an incoming phone call, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook. When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message.

Let's see how we would build this in Java using the Spark(link takes you to an external page) web application framework. Spark is a lightweight web application framework and is completely different from the big data software named Apache Spark.

Spark requires its own library, separate from the Twilio Java helper library, which you can install using the directions on the Download Spark Java(link takes you to an external page) page. You'll find directions for using Spark with Maven, Gradle, or as a standalone download. Spark does not come with a logging implementation, but it does work with the Simple Logging Facade 4 Java (SLF4J)(link takes you to an external page), which you can also include in your Java classpath.

You can certainly set up all of your dependencies on the command line like we did in the above section when we made a phone call through Twilio, but it's a little easier to get everything set up using a Java integrated development environment (IDE). We are going to use the free, community edition of IntelliJ IDEA, which you can download from JetBrains(link takes you to an external page). You can download JAR files and use them directly with IntelliJ IDEA, or you can use a dependency manager such as Maven or Gradle. We will use Gradle with IntelliJ IDEA to build our application.

Creating a web application with IntelliJ IDEA and Gradle

creating-a-web-application-with-intellij-idea-and-gradle page anchor

If you haven't downloaded and installed IntelliJ IDEA Community Edition(link takes you to an external page), please go ahead and do that now! After you run IDEA for the first time, you will see a screen that looks like this:

Start IDEA.

Choose 'Create New Project,' and the new New Project wizard will start:

New Gradle Project with IntelliJ IDEA.

On the left-hand side of that dialog box, choose Gradle (instead of Java), so that IntelliJ IDEA will set your project up to use Gradle for dependency management. You could also choose to use Maven here instead - the process is almost the same.

After choosing Gradle, verify that IntelliJ IDEA has a project SDK (you'll need Java 8 or higher, so version 1.8 or above), and then click Next.

Voice Quickstart Project Naming with IntelliJ IDEA.

On the next screen in the wizard, you will be asked for a group id, an artifact id, and a version number. For the group id, you can use a reverse domain name, such as com.yourcompany.voice, and for the artifact id, you should use your project name, like voice-quickstart-app. You can leave the version as 1.0-SNAPSHOT. After filling in these fields, click Next.

Gradle Settings.

On this Gradle settings screen, you can leave the defaults and then click Next.

Intellij IDEA Project Location.

Last, you can confirm the project name and project directory to use for your Quickstart web application. The defaults are probably fine here as well. Clicking Finish will take you to your new IntelliJ Project. If you just installed IntelliJ IDEA, the IDE will download Gradle and do some setup and installation.

Gradle Sync during Java Voice Quickstart Setup.

Now that we've got our project all set up, we just have a few more steps! We'll need the Twilio Java helper library, and the Spark Java web application framework as dependencies, along with the logging implementation so that we can see status messages from Spark. With Gradle, we can add those to the build.gradle file that IntelliJ created for us. Go ahead and find build.gradle in the sidebar and click on it to open it.

Voice Quickstart for Java build.gradle file

voice-quickstart-for-java-buildgradle-file page anchor

_17
group 'com.twilio.quickstart.voice'
_17
version '1.0-SNAPSHOT'
_17
_17
apply plugin: 'java'
_17
_17
sourceCompatibility = 1.8
_17
_17
repositories {
_17
mavenCentral()
_17
}
_17
_17
dependencies {
_17
testCompile group: 'junit', name: 'junit', version: '4.12'
_17
compile group: "com.twilio.sdk", name: "twilio", version: "7.17.+"
_17
compile group: "com.sparkjava", name: "spark-core", version: "2.7.1"
_17
compile group: "org.slf4j", name: "slf4j-simple", version: "1.7.21"
_17
}


Add dependencies in build.gradle

add-dependencies-in-buildgradle page anchor

You'll need to add three lines to your build.gradle file, in the dependencies group:

compile group: "com.twilio.sdk", name: "twilio", version: "8.0.+"
compile group: "com.sparkjava", name: "spark-core", version: "2.7.1"
compile group: "org.slf4j", name: "slf4j-simple", version: "1.7.21"
With these three dependencies, Gradle will download the appropriate libraries for you and add them to the classpath for building and running your Java application.

Now that we have all of that out of the way, it's time to write some code!


Respond to an incoming phone call

respond-to-an-incoming-phone-call page anchor

We'll need to start by creating a Java class in our project. In IntelliJ IDEA, select the java folder under src and main. Next, open the File menu at the top of the screen. Choose the New submenu, and then Java Class.

A small popup window will appear, and you can create a new class. Name your class VoiceApp - capitalization is important because it has to match the code sample.

Create new VoiceApp class.

You should have an VoiceApp.java source code file now. Copy and paste the code from the code sample into that source code file.

This Java code will listen for inbound HTTP GET requests to '/hello', respond with "Hello Web," and listen to inbound HTTP POST requests for '/', and respond with TwiML markup!.

Generate TwiML to Say a message

generate-twiml-to-say-a-message page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
xml

_16
const http = require('http');
_16
const VoiceResponse = require('twilio').twiml.VoiceResponse;
_16
_16
http
_16
.createServer((req, res) => {
_16
// Create TwiML response
_16
const twiml = new VoiceResponse();
_16
_16
twiml.say('Hello from your pals at Twilio! Have fun.');
_16
_16
res.writeHead(200, { 'Content-Type': 'text/xml' });
_16
res.end(twiml.toString());
_16
})
_16
.listen(1337, '127.0.0.1');
_16
_16
console.log('TwiML server running at http://127.0.0.1:1337/');

After you get your code in place, you can right-click on the VoiceApp class in the project outline on the left-hand side, and then choose the Run 'VoiceApp.main()' menu item.

The Java spark web application server will start listening on port 4567.

Try going to http://localhost:4567/hello to verify that your server is working - you should see "Hello Web" in your web browser.

(warning)

Warning

One important thing to note - if you make a change to your code, and want to run the server again, you will need to stop the currently running application with the red stop button. Only one application can use port 4567 at a time, so if you run your Java application while an older version is still running, the new application will immediately exit.

You'll need to make your application accessible over the internet. While you can do that in any number of ways, we recommend a tool that provides an externally accessible URL called ngrok(link takes you to an external page). We'll show you how to set that up next so your app can receive phone calls.


Allow Twilio to talk to your Java application with ngrok

allow-twilio-to-talk-to-your-java-application-with-ngrok page anchor

We've just built a small Java web application to receive incoming phone calls. Before it will work, we need to make sure that Twilio can reach our application.

Most Twilio services use webhooks to communicate with your application. When Twilio receives an incoming phone call, for example, it reaches out to a URL in your application for instructions on how to handle the message.

When you're working on your Java web application in your development environment, your app is only reachable by other programs on your computer, so Twilio won't be able to talk to it. We need to solve this problem by making your application accessible over the internet.

While there are a lot of ways to do this, like deploying your application to Heroku or AWS, you'll probably want a less laborious way to test your Twilio application. For a lightweight way to make your app available on the internet, we recommend a tool called ngrok(link takes you to an external page). Ngrok listens on the same port that your local web server is running on and provides a unique URL on the ngrok.io domain, forwarding incoming requests to your local development environment. It works something like this:

How ngrok helps Twilio reach your local server.

If you haven't already, install ngrok(link takes you to an external page). Make sure it's the ngrok version that's appropriate for your operating system and take care that the 'ngrok' command is on your system path. If you're working on a Mac or Linux, you're all set. If you're on Windows, follow our guide on how to install and configure ngrok on Windows. For more info on ngrok, including some great tips and tricks, check out this in-depth blog post(link takes you to an external page).

The following command would use ngrok to expose port 4567 to the public Internet. Type the following command on the command line:


_10
ngrok http 4567

And you will see output similar to this:

ngrok terminal output.

Now we have a new external URL.

Configure your webhook URL

configure-your-webhook-url page anchor

Now, you must take that public URL and configure this as a webhook for one of your phone numbers(link takes you to an external page) in the console. Go back to the console, select your phone number, change "A CALL COMES IN" to Webhook, and then put in the external URL to your service, such as "https://069a61b7.ngrok.io/(link takes you to an external page)", as shown above.

Where to put ngrok URL for webhook.

Save your changes - you're ready!

Make sure you are running your 'ngrok' command on the command line, and running your web application from IntelliJ IDEA. If you restarted ngrok, you will have to update your webhook in the console to use the right url.

With both of those servers running, we're ready for the fun part - testing our new Java web application!

Call the Twilio phone number you configured with this webhook. You should see an HTTP POST request with a 200 OK in your ngrok console. Your Java web application will reply back to Twilio with your TwiML response, and you'll hear your message being read to you!


Now you know the basics of making and responding to phone calls with Java.

This app only used the <Say> TwiML verb to read a message to the caller using text to speech. With different TwiML verbs, you can create other powerful constructs and call flows. Try a few, such as <Record>, <Gather>, and <Conference>.

Check out these pages to learn more:

Happy hacking!


Rate this page: