How to Integrate Ngrok in a Twilio Java Application

November 22, 2021
Written by
Diane Phan
Twilion
Reviewed by

header - How to Integrate Ngrok in a Twilio Java Application

When you are developing an application that uses Twilio services you need to expose your webhooks on public URLs that can be reached by Twilio. If you have followed some of the tutorials that we published on this blog you know that we recommend using the excellent ngrok tool to generate temporary public URLs for your development web server. Ngrok is an incredibly useful tool that creates a tunnel from a URL on the ngrok.io domain to your application running on your computer. You can then configure your webhook using the ngrok URL and when Twilio sends a request to it, ngrok redirects it to your application.

If you use ngrok frequently enough, it pays off to become a paid customer, which allows you to secure a permanent URL.

In this article I’m going to show you how to fully automate ngrok by incorporating it into your Java application.

Prerequisites

Log onto the Twilio Dashboard to view your Active Numbers. Click on the number you want to use to view the details. If you haven’t purchased a number yet, learn how to search for and buy a Twilio phone number.

Start a new Java project in IntelliJ IDEA

Open IntelliJ IDEA and click on Create New Project.

IntelliJ IDEA home screen

Choose Gradle on the left hand side and check Java in the box on the right hand side. Make sure that you use Java 8 or 11 as they are long-term supported versions.

choose gradle option for new java project

Click Next to continue on to the next page. Give your project a name such as "SmsApp", and click the Finish button.

After the project setup is complete, your project directory structure should look like the following image:

project directory for the build gradle file

Open the build.gradle file in the IDE and add the following lines inside the dependencies block:

    implementation group: "com.twilio.sdk", name: "twilio", version: "8.0.+"
    implementation group: "com.sparkjava", name: "spark-core", version: "2.9.3"
    implementation group: "org.slf4j", name: "slf4j-simple", version: "1.7.32"
    implementation "com.github.alexdlaird:java-ngrok:1.5.5"

In order to fully integrate and create a client to ngrok, we need to incorporate Alex Laird's java-ngrok wrapper so that we can conveniently use ngrok in our application.

Create the SMS app's Java class

Expand the main subfolder under the src folder at the root of the project directory. Notice the empty java folder.

project directory for the java subfolder

Right click on the Java folder and click on the New option. Select Java Class as seen in the image below. Clicking this option will prompt you to give the class a name. Go ahead and name it "SmsApp".

Create a new Java class in Intellij IDEA

Copy and paste the following code into the newly created file:

import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.messaging.Body;
import com.twilio.twiml.messaging.Message;
import static spark.Spark.*;
import com.github.alexdlaird.ngrok.NgrokClient;
import com.github.alexdlaird.ngrok.protocol.CreateTunnel;
import com.github.alexdlaird.ngrok.protocol.Region;
import com.github.alexdlaird.ngrok.protocol.Tunnel;

public class SmsApp {
    public static void main(String[] args) {
        port(80);
    }
}

It is important to know that the Java class' filename must reflect the class name within the file.

In the public SmsApp class, a main method is invoked so that the code in the program starts once executed. For the time being, the ngrok HTTP tunnel will connect to the default port 80.

Write the SMS POST route for the Java class

In order to put ngrok to the test, we'll create a POST route which responds with TwiML markup for an SMS response. This Body object is created to hold the string message.

Copy and paste the following code inside of the main function and under the port(80) declaration:  

        post("/sms", (req, res) -> {
            res.type("application/xml");
            Body body = new Body
                    .Builder("✨It's fun to send sparkly texts! ✨")
                    .build();
            Message sms = new Message
                    .Builder()
                    .body(body)
                    .build();
            MessagingResponse twiml = new MessagingResponse
                    .Builder()
                    .message(sms)
                    .build();
            return twiml.toXml();
        });

Open the ngrok tunnel

After defining the functionality of the POST route, the ngrok client and tunnel need to be initialized.

Copy and paste the following code inside the main function and below the POST route:

        final NgrokClient ngrokClient = new NgrokClient.Builder().build();
        final CreateTunnel createTunnel = new CreateTunnel.Builder()
                .build();
        final Tunnel tunnel = ngrokClient.connect(createTunnel);

The final keyword is added to restrict the variable from being modified. You can view the documentation for declaring and using the ngrok in the GitHub README.

At this point, you should have a simple POST route that creates an SMS with Twilio's API and a connection to a tunnel from the ngrok client. Save the program.

Run the Java ngrok application

Right click on the SmsApp file in the project interface and find the option to Run 'SmsApp.main()'. Wait a few seconds for the project to build, download the project's dependencies, and compile.

Soon, the terminal should display a link to the default port 80 as well as a randomly generated link. You may have to scroll down the output text for a bit until you find a URL similar to “https://ad7e4814affe.ngrok.io/”. Here's an example of the output you might have to scroll through:

example ngrok output from running the main java program

NOTE: Keep in mind that this URL is no longer active and only presented here for demonstration purposes.

Set up the webhook with Twilio

Copy the Forwarding URL starting with https:// and open the Twilio Console, where we will tell Twilio to send incoming message notifications with this URL.

In the Twilio Console, click on the left sidebar to explore products, and find Phone Numbers. Click on the active phone number that you want to use for this project and scroll down to “Messaging”.

There, paste the URL copied from the ngrok session into the A MESSAGE COMES IN field and append /sms, since that is the endpoint. Before you click on the Save button, make sure that the request method is set to HTTP POST.

Here is my example for reference:

input the unique ngrok url webhook with a route directing to sms

Send a text message to the Twilio number

Send a text message to your Twilio phone number on your mobile device. Wait a few seconds and you should see the TwiML message response on your device.

screenshot of the example SMS interaction between the java spark app and user

What's next for building Java projects?

Congratulations on sending an SMS text message on your Java application! But don't stop here. Check out these articles on how you can build more with Twilio and Java:  

Let me know about the projects you're building with Java and Twilio by reaching out to me over email!

Diane Phan is a software developer on the Developer Voices team. She loves to help programmers tackle difficult challenges that might prevent them from bringing their projects to life. She can be reached at dphan [at] twilio.com or LinkedIn.