Programmable Messaging Quickstart for Java
Ahoy there! All messaging transmitted using Twilio’s messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio’s Messaging Policy. For detailed information on policy rules to ensure you remain compliant while using Twilio’s services, please see our Acceptable Use Policy.
Ready to start sending and receiving text messages with Twilio Programmable SMS using Java?
This Programmable SMS Quickstart for Java will teach you how to do this using the Twilio Java helper library for our Communications REST API.
このクイックスタートでは、下記のことを学んでいきます:
- Twilioにサインアップして、SMS機能を持ったはじめてのTwilio電話番号を入手する
- メッセージを送受信できるように開発環境をセットアップする
- 最初のSMSを送信する
- テキストメッセージを受信する
- 受信メッセージに対してSMSで返信する
ビデオを見ながらの入門がお好みですか? YouTube上のJava SMSクイックスタートビデオ(英語)をご覧ください。
Sign up for - or sign in to - Twilio
Already have a Twilio account? Go ahead and skip this section.
You can sign up for a free Twilio trial account here.
- When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
- Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
- Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID an authentication token, find a Twilio phone number, and more.
Install the Twilio CLI
We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.
The suggested way to install twilio-cli
on macOS is to use Homebrew. If you don’t already have it installed, visit the Homebrew site for installation instructions and then return here.
Once you have installed Homebrew, run the following command to install twilio-cli
:
brew tap twilio/brew && brew install twilio
The suggested way to install twilio-cli
is by using Scoop, a command-line installer for Windows. If you don’t already have it installed, visit the Scoop site for installation instructions and then return here.
Note PowerShell will need to be run as an administrator to avoid common permission issues when installing via Scoop.
- Add the
twilio-cli
Bucket:
scoop bucket add twilio-scoop https://github.com/twilio/scoop-twilio-cli
- Install the app:
scoop install twilio
twilio-cli
can be installed using the Advanced Package Tool (apt
) on most distributions such as Debian, Ubuntu, and Mint.
To do so, run the following commands in your terminal:
wget -qO- https://twilio-cli-prod.s3.amazonaws.com/twilio_pub.asc \
| sudo apt-key add -
sudo touch /etc/apt/sources.list.d/twilio.list
echo 'deb https://twilio-cli-prod.s3.amazonaws.com/apt/ /' \
| sudo tee /etc/apt/sources.list.d/twilio.list
sudo apt update
sudo apt install -y twilio
For other installation methods, see the Twilio CLI Quickstart.
Run twilio login
to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.
認証トークンは、目玉アイコンをクリックすると表示されます:
Get a phone number
If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. With the CLI, run:
twilio phone-numbers:buy:local --country-code US --sms-enabled
Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren't finding any SMS enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled
Select a phone number to add it to your account.
Next, we need to install Java and the Twilio Java Helper Library.
Java環境をセットアップする
すでにJavaの開発環境のセットアップがすべて済んでおり、Twilio Javaヘルパーライブラリーがクラスパスに構成されていますか? その場合はどうぞ次の2つの節を読み飛ばして、Twilioを使用した最初のテキストメッセージの送信までお進みください!
To send your first SMS, 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:
javac -version
下記の出力のようになります:
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.
スタンドアローンのTwilio Javaヘルパーライブラリーをダウンロードする
Javaのセットアップがすべて完了して先に進む準備ができましたか? お見事!
Next, download the standalone Twilio Java Helper Library. 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. We'll be using this "fat jar" file with all the dependencies in this SMS Quickstart. When you download the fat 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? The Twilio Java Helper Library docs have information on how to install using a build automation tool.
このTwilio JavaヘルパーライブラリーはAndroidアプリケーションでの使用を想定しているものではありません! サーバー、コマンドラインアプリケーション、およびこれらと同種のプロジェクトにこのライブラリーを使用してください。
モバイルアプリケーションからSMSを送信したい場合は、Twilioのクレデンシャルを伴ったサーバーコンポーネントをご用意いただき、アプリケーションからはこちらにHTTPリクエストを送信します。 TwilioのアカウントSIDと認証トークンがエンドユーザーの手に渡ることは、お使いのTwilioアカウントをセキュリティー上のリスクに晒すことにつながります。
JavaでSMSメッセージを送信する
これでJDKとTwilio Javaヘルパーライブラリーがインストールできたので、今しがた購入したTwilio電話番号から、1回のAPIリクエストでSMSを送信できます。 SmsSender.java
という名前の新規ファイルを作成して開き、下記のコードサンプルを打ち込むかペーストします。
メッセージの送信前に、このファイルを少々編集する必要があります:
プレースホルダーのクレデンシャル値を置き換える
Swap the placeholder values for ACCOUNT_SID
and AUTH_TOKEN
with your personal Twilio credentials. Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on the eyeball icon:
SmsSender.java
を開き、ACCOUNT_SID
およびAUTH_TOKEN
に対応する値をご使用のアカウントの一意な値に置き換えます。
ご注意ください: 初めのうちは認証情報をハードコーディングしても構いませんが、本番環境にデプロイするにあたっては、環境変数を使用してこれらが漏洩しないようにしてください。 追加情報については、環境変数の設定方法を参照してください。
「From」電話番号を置き換える
数分前に購入した、SMS機能対応の電話番号を覚えていますか? どうぞ、既存のfrom
番号をご自身の番号に置き換えてください。 また、E.164形式が使用されていることも確認します。
[+][country code][phone number including area code]
「To」電話番号を置き換える
Replace the to
phone number with your mobile phone number. This can be any phone number that can receive text messages, 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.
変更を保存し、ターミナルからこのJavaクラスを実行します:
javac -cp twilio-8.0.0-jar-with-dependencies.jar SmsSender.java
コマンドラインからクラスをコンパイルするには、依存関係を伴ってこのTwilio jarをインクルードすることが必要です。 IntelliJ IDEA、Netbeans、あるいはEclipseといったような統合開発環境をお使いの場合、他の依存関係と同様にTwilio jarをご自身のクラスパスまたはプロジェクトライブラリーに単に追加することができます。 またMavenやGradleのようなビルドツールも使用可能で、Twilioのヘルパーライブラリーを依存関係として記述するだけでJavaアプリケーションをビルド、実行できます。
Javaクラスのビルドが完了したら、これを実行することが必要です。 macOSまたはLinux上でコマンドラインから実行している場合は、下記のようなコマンドになります:
java -cp .:twilio-8.0.0-jar-with-dependencies.jar SmsSender
Windowsでの対応するコマンドは以下のとおりです:
java -cp ".;twilio-8.0.0-jar-with-dependencies.jar" SmsSender
相違点としては、コマンドラインでのJavaクラスパスの区切り記号はWindowsではセミコロンであり、macOSまたはLinuxではコロンであるという点が挙げられます。
一丁上がり! ほどなくして、Twilio電話番号から携帯電話にSMSが受信されるはずです。
あなたのお客様は米国またはカナダにお住まいですか? もう1行コードを追加すれば、MMSメッセージの送信も可能です。 方法を確認するには、MMS送信のガイドを参照してください。
トライアルアカウントをご使用の場合、Twilioで検証済みの電話番号に送信先が制限されます。電話番号はTwilioコンソール内の検証済み発信者番号にて検証できます。
メッセージを受信、返信を行う
When your Twilio number receives an incoming message, 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.
Spark Webアプリケーションフレームワークを使用して、Javaでこれをビルドする方法を見ていきましょう。 Sparkは軽量なWebアプリケーションフレームワークであり、ビッグデータソフトウェアの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 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), which you can also include in your Java classpath.
上記でTwilioを使用しSMSを送信した時点で、ここの解説のようにコマンドライン上ですべての依存関係のセットアップが済んでいることでしょう。 しかしJavaの統合開発環境 (IDE=Integrated Development Environment) を使用するとセットアップ全過程が少しだけ、より簡単になります。 ここではJetBrainsからダウンロード可能な、IntelliJ IDEAの無料のCommunity Editionを使用します。 IntelliJ IDEAで直接JARファイルをダウンロード、使用できるほか、MavenやGradleのような依存関係マネージャーを使用することもできます。 今回のアプリケーションのビルドには、IntelliJ IDEAをGradleと組み合わせて使用することにします。
IntelliJ IDEAおよびGradleを使用してWebアプリケーションを作成する
IntelliJ IDEA Community Editionをまだダウンロード、インストールしていない場合は、どうぞ行なってください! 初回にIDEAを実行すると、下記のような画面が表示されます:
Choose 'Create New Project,' and the new New Project wizard will start:
ダイアログボックスの左側で、 (Javaではなく) Gradleを選択すると、IntelliJ IDEAは依存関係の管理にGradleを使用するようプロジェクトをセットアップします。 ここでは代わりにMavenを選択することもできます。 手順はほぼ同じです。
Gradleの選択後、IntelliJ IDEAにプロジェクトSDK (Java 8以降、すなわちバージョン1.8以上が必要です) があることを確認し、Nextをクリックします。
ウィザードの次の画面では、group id
、artifact id
、そしてversion number
が尋ねられます。 group idには、com.yourcompany.sms といったようなリバースドメイン名が使用できます。 またartifact idには、sms-quickstart-app のようなプロジェクト名を使用してください。 version は 1.0-SNAPSHOTのままで構いません。 これらのフィールドの入力が済んだら、Nextをクリックします。
Gradle設定画面では、既定値のままでNextをクリックします。
最後に、クイックスタートWebアプリケーションに使用するプロジェクト名とプロジェクトディレクトリーを確認します。 こちらも同様に、既定値のままで問題ありません。 Finishをクリックすると、新規のIntelliJプロジェクトが表示されます。 IntelliJ IDEAをインストールしたばかりの場合は、IDEはGradleをダウンロードし、セットアップとインストールがいくつか行われます。
これでプロジェクト設定がすべて完了しました。 残る手順はあと少しです! 依存関係としてTwilio JavaヘルパーライブラリーとSpark Java Webアプリケーションフレームワークが必要になります。 またSparkからのステータスメッセージを表示できるようにするためのログ記録の実装も必要です。 これらをGradleを使用して、IntelliJによって作成されたbuild.gradleに追加できます。 さぁ、サイドバーでbuild.gradle
を探しクリックして開いてください。
build.gradleに依存関係を追加する
build.gradle
ファイルのdependenciesグループに下記の行を追加することが必要です:
implementation group: "com.twilio.sdk", name: "twilio", version: "8.0.+"
implementation group: "com.sparkjava", name: "spark-core", version: "2.7.1"
implementation group: "org.slf4j", name: "slf4j-simple", version: "1.7.21"
これらの3つの依存関係で、Gradleは適切なライブラリーをダウンロードし、ビルドと実行を行うためにクラスパスに追加します。
これでひととおり作業が完了したので、これからコーディングを少し行いましょう!
受信テキストメッセージに返信する
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.
小さいポップアップウィンドウが表示され、新規クラスを作成できます。 クラスに SmsApp
という名前をつけます。 大文字と小文字の区別は重要です。 これらがコードサンプルと一致している必要があるためです。
SmsApp.java
ソースコードファイルが確認できるはずです。 コードサンプルからこのソースコードファイルにコードサンプルからコードをコピー&ペーストを使用します。
このJavaコードは「/」への受信HTTP GETリクエストをリッスンし、また「/SMS」への受信HTTP POSTリクエストもリッスン、SMSメッセージに対するTwiMLマークアップでレスポンスを返します。
コードの準備が整ったら、左側のプロジェクトアウトラインからSmsAppクラスを右クリックできるので、Run 'SmsApp.main()' メニュー項目を選択します。
Java Spark Webアプリケーションサーバーはポート4567でリッスンを開始ます。 Webブラウザーでhttp://localhost:4567/にアクセスしてこれを確認できます。
覚えておきたい重要事項: コードの変更を行いサーバーを再度実行したい場合、赤い停止ボタンで現在実行中のアプリケーションを停止させることが必要です。 同時に1つのアプリケーションのみがポート4567を使用できるため、旧バージョンが依然実行中の状態でJavaアプリケーションを実行すると、新しいアプリケーションはすぐに終了します。
That's all the code you need - there's just one more step before everything is wired up.
WebhookのURLを設定する
Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:
twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:4567/sms"
The CLI will start an ngrok tunnel (so Twilio can reach your development machine) and wait patiently for incoming text messages!
SMSを送信しアプリケーションをテストする
これですべての設定が完了したので、いよいよテストしてみましょう。
Send a text message from your mobile phone to your Twilio phone number. Twilio will forward your response back as an SMS!
関連トピック
Javaを使用したメッセージ送受信の基本について理解できたところで、下記の資料について調べてみるのも良いかもしれません。
- Messaging API documentation
- TwiMLリファレンス・ドキュメント
- Java用の完全なサンプルアプリケーションを含むチュートリアル
- 0 to 60 with Java – Sending an SMS in a Minute (英語)
楽しいプログラミングを!
ヘルプが必要ですか?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.