Get Started

Twilio Client Java Quickstart

Make Outgoing Calls from the Browser

Cool, you have now used Twilio Client to call into your browser and have a conversation. Rock on!

Now, let's make a more useful application that can actually do something by passing arbitrary data from the browser to your TwiML script.

This tutorial assumes you have a Java development environment with a Web server capable of running Java servlets and the twilio-java helper library. Please see our post on setting up your environment if you need help installing those programs.

Let's say that you want the browser to dial and connect you to any phone number. That's easy to do; here's how:

  • Add a text box to the /client URL route, so that you can enter a phone number.
  • Pass that phone number along in the Twilio.Device.connect() call.
  • Update the /voice URL route to serve a TwiML snippet that contains a <Dial> verb with the phone number you passed in from the browser.

The complete source code is shown below with the new additions highlighted. We now get the phone number from an HTML text box, put it in an array of parameters with the key PhoneNumber, and pass those parameters to Twilio.Device.connect() when you click the 'Call' button. Simple!

client/client.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Hello Client Monkey 4</title>
        <script type="text/javascript"
          src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
        <script type="text/javascript"
          src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
        </script>
        <link href="http://static0.twilio.com/packages/quickstart/client.css"
          type="text/css" rel="stylesheet" />
        <script type="text/javascript">

        Twilio.Device.setup("${token}", {debug: true});

          Twilio.Device.ready(function (device) {
            $("#log").text("Ready");
          });

          Twilio.Device.error(function (error) {
            $("#log").text("Error: " + error.message);
          });

          Twilio.Device.connect(function (conn) {
            $("#log").text("Successfully established call");
          });

          Twilio.Device.disconnect(function (conn) {
            $("#log").text("Call ended");
          });

          Twilio.Device.incoming(function (conn) {
            $("#log").text("Incoming connection from " + conn.parameters.From);
            // accept the incoming connection and start two-way audio
            conn.accept();
          });

          function call() {
            // get the phone number to connect the call to
            params = {"PhoneNumber": $("#number").val()};
            Twilio.Device.connect(params);
          }

          function hangup() {
            Twilio.Device.disconnectAll();
          }
        </script>
      </head>
      <body>
        <button class="call" onclick="call();">
          Call
        </button>

        <button class="hangup" onclick="hangup();">
          Hangup
        </button>

        <input type="text" id="number" name="number"
          placeholder="Enter a phone number to call"/>

        <div id="log">Loading pigeons...</div>
      </body>
    </html>

Now, the TwiML script needs to receive the PhoneNumber parameter given to it when Twilio makes a request to the Voice URL. Let's change the /voice URL route to read the PhoneNumber parameter and insert that value into the <Dial> verb. If the PhoneNumber parameter isn't given, we can default to calling "jenny" as we did before. The complete TwiML script is shown below with the new and changed lines highlighted.

client/WEB-INF/classes/com/twilio/TwilioVoiceServlet.java
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Dial;
import com.twilio.sdk.verbs.Client;
import com.twilio.sdk.verbs.Number;

public class TwilioVoiceServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String phoneNumber = request.getParameter("PhoneNumber");

        /* Use this as the caller ID when making calls from a browser. */
        String callerId = "+14105551234";

        TwiMLResponse twiml = new TwiMLResponse();
        Dial dial = new Dial();
        try {
            if (phoneNumber != null) {
                dial.append(new Number(phoneNumber));
                dial.setCallerId(callerId);
            } else {
                dial.append(new Client("jenny"));
            }
            twiml.append(dial);
        } catch (TwiMLException e) {
            e.printStackTrace();
        }
        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}


Once again, let's load that URL in your browser to make sure the script renders the TwiML snippet correctly. But this time, specify the PhoneNumber parameter in the URL, like this: http://example.com/<path-to-servlet>/voice?PhoneNumber=14158675309.

Since we want to be able to call phone numbers or other browsers, we've made the TwiML script accept either. If a PhoneNumber parameter is specified, we'll assume we should dial a phone number. In that case, we put the value of the PhoneNumber parameter inside a <Number> noun. Otherwise, we'll assume it's a client, so we put the value inside a <Client> noun.

Notice that we added a callerId attribute to the <Dial> verb. To call a phone from the browser using Twilio Client, you must specifiy a caller ID. Without this attribute, the call will fail and an "invalid callerId value" error will appear in your Twilio Debugger. Any of your Twilio phone numbers or verified caller IDs will work.

If you want to call a traditional telephone, you'll need to either buy a Twilio number or verify a number you already own to use as the caller ID when calling from Twilio Client.

So, go ahead and load up http://example.com/<path-to-servlet>/client, enter your cell phone number in the box and press the 'Call' button. Your phone will ring and you can talk to yourself... Huzzah!

But with Twilio Client, who needs a phone? Now, it's about time to make a call between two browsers.


Next: Making Browser-to-Browser Calls »