1. Introduction
1.绪论
Sending SMS messages is a big part of many modern applications. There are a variety of uses cases that SMS messages can serve: two-factor authentication, real-time alerts, chatbots, and many more.
发送短信是许多现代应用的一个重要部分。短信有多种用途:双因素认证、实时警报、聊天机器人,以及更多。
In this tutorial, we’ll build a simple Java application that sends SMS messages using Twilio.
在本教程中,我们将建立一个简单的Java应用程序,使用Twilio发送SMS消息。
There are a number of services that provide SMS capabilities, such as Vonage, Plivo, Amazon Simple Notification Service (SNS), Zapier, and more.
有许多服务提供了短信功能,例如Vonage、Plivo、AmazonSimple Notification Service (SNS)、Zapier等。
Using the Twilio Java client, we can send an SMS message in just a few lines of code.
使用Twilio Java客户端,我们只需几行代码就可以发送一条SMS消息。
2. Setting up Twilio
2.设置Twilio
To get started we’ll need a Twilio account. They offer a trial account that is sufficient for testing every feature of their platform.
为了开始工作,我们需要一个Twilio账户。他们提供了一个试用账户,足以测试他们平台的每个功能。
As part of the account setup, we must also create a phone number. This is important because the trial account requires a verified phone number for sending messages.
作为账户设置的一部分,我们还必须创建一个电话号码。这很重要,因为试用账户需要一个经过验证的电话号码来发送信息。
Twilio offers a quick setup tutorial for new accounts. Once we complete the account setup and verify our phone number, we can start sending messages.
Twilio为新账户提供了一个快速设置教程。一旦我们完成了账户设置并验证了我们的电话号码,我们就可以开始发送消息了。
3. Introduction to TwiML
3.TwiML简介
Before we write our sample application, let’s take a quick look at the data exchange format used for Twilio services.
在编写我们的示例应用程序之前,让我们快速浏览一下Twilio服务使用的数据交换格式。
TwiML is a proprietary markup language based on XML. The elements in a TwiML message mirror the different actions we can take related to telephony: make a phone call, record a message, send a message, and so on.
TwiML是一种基于XML的专有标记语言。TwiML信息中的元素反映了我们可以采取的与电话有关的不同行动:拨打电话、录制信息、发送信息等等。
Here is an example TwiML message for sending an SMS:
下面是一个发送短信的TwiML消息的例子。
<Response>
<Message>
<Body>Sample Twilio SMS</Body>
</Message>
</Response>
And here is another example TwiML message that makes a phone call:
下面是另一个拨打电话的TwiML消息的例子。
<Response>
<Dial>
<Number>415-123-4567</Number>
</Dial>
</Response>
These are both trivial examples, but they give us a good understanding of how TwiML looks like. It’s composed of verbs and nouns that are easy to remember and directly relate to the action we’d perform with a phone.
这两个例子都是微不足道的,但它们让我们很好地了解了TwiML的样子。 它是由动词和名词组成的,这些动词和名词很容易记住,并与我们用手机进行的操作直接相关。
4. Sending SMS in Java with Twilio
4.用Twilio在Java中发送短信
Twilio provides a rich Java client that makes interacting with their services easy. Instead of having to write code that builds TwiML messages from scratch, we can use an out-of-the-box Java client.
Twilio提供了一个丰富的Java客户端,使得与他们的服务进行交互变得很容易。我们不必编写从头开始构建TwiML消息的代码,而是可以使用一个开箱即用的Java客户端。
4.1. Dependencies
4.1. 依赖性
We can download the dependency directly from Maven Central or by adding the following entry to our pom.xml file:
我们可以直接从Maven中心下载该依赖项,或者在pom.xml文件中添加以下条目。
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.20.0</version>
</dependency>
4.2. Sending an SMS
4.2.发送短信
To get started, let’s look at some sample code:
为了开始,让我们看一下一些示例代码。
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
new PhoneNumber("+12225559999"),
new PhoneNumber(TWILIO_NUMBER),
"Sample Twilio SMS using Java")
.create();
Let’s break down into key pieces the code in the above sample:
让我们把上述例子中的代码分解成关键部分。
- The Twilio.init() call is required once to set up the Twilio environment with our unique Account Sid and Token
- The Message object is the Java equivalent to the TwiML <Message> element we saw earlier
- Message.creator() requires 3 parameters: To phone number, From phone number, and the message body
- The create() method handles sending the message
4.3. Sending an MMS
4.3.发送彩信
The Twilio API also supports sending multimedia messages. We can mix and match text and images, for this to work the receiving phone must support media messaging:
Twilio API还支持发送多媒体信息。我们可以混合和匹配文本和图像,要做到这一点,接收电话必须支持媒体信息。
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
new PhoneNumber("+12225559999"),
new PhoneNumber(TWILIO_NUMBER),
"Sample Twilio MMS using Java")
.setMediaUrl(
Promoter.listOfOne(URI.create("http://www.domain.com/image.png")))
.create();
5. Tracking Message Status
5.追踪信息状态
In the previous examples, we didn’t confirm if the message was actually delivered. However Twilio provides a mechanism for us to determine whether a message was successfully delivered or not.
在前面的例子中,我们并没有确认消息是否真的被送达。然而Twilio为我们提供了一种机制来确定消息是否被成功传递。
5.1. Message Status Codes
5.1 信息状态代码
When sending a message, it’ll have one of the statuses at any time:
在发送信息时,它在任何时候都会有其中一种状态。
- Queued – Twilio has received the message and queued it for delivery
- Sending – the server is in the process of dispatching your message to the nearest upstream carrier in the network
- Sent – the message was successfully accepted by the nearest upstream carrier
- Delivered – Twilio has received confirmation of message delivery from the upstream carrier, and possibly the destination handset when available
- Failed – the message couldn’t be send
- Undelivered – the server has received a delivery receipt indicating the message wasn’t delivered
Note that for the last two statuses we can find an error code with more specific details to help us troubleshoot delivery problems.
请注意,对于后两种状态,我们可以找到一个有更多具体细节的错误代码,以帮助我们排除交付问题。
The Twilio Java Client offers a synchronous and asynchronous methods to fetch status. Let’s have a look.
Twilio Java客户端提供了一个同步和异步的方法来获取状态。让我们看一下。
5.2. Checking Delivery Status (Synchronous)
5.2.检查交付状态(同步)
Once we’ve created a Message object, we can call Message.getStatus() to see which status it’s currently in:
一旦我们创建了一个Message对象,我们就可以调用Message.getStatus()来查看它当前所处的状态。
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ResourceSet messages = Message.reader().read();
for (Message message : messages) {
System.out.println(message.getSid() + " : " + message.getStatus());
}
Note that Message.reader().read() makes a remote API call so use it sparingly. By default, it returns all messages we’ve sent, but we can filter the returned messages by phone numbers or date range.
请注意,Message.reader().read()会进行远程API调用,所以要少用。默认情况下,它返回我们发送的所有信息,但我们可以通过电话号码或日期范围过滤返回的信息。
5.3. Checking Delivery Status (Async)
5.3.检查交付状态(异步)
Because retrieving message status requires a remote API call, it can take a long time. To avoid blocking the current thread, the Twilio Java client provides also an asynchronous version of Message.getStatus().read().
因为检索消息状态需要远程调用API,所以可能需要很长的时间。为了避免阻塞当前线程,Twilio Java客户端还提供了一个异步版本的Message.getStatus().read()。
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ListenableFuture<ResourceSet<Message>> future = Message.reader().readAsync();
Futures.addCallback(
future,
new FutureCallback<ResourceSet<Message>>() {
public void onSuccess(ResourceSet<Message> messages) {
for (Message message : messages) {
System.out.println(message.getSid() + " : " + message.getStatus());
}
}
public void onFailure(Throwable t) {
System.out.println("Failed to get message status: " + t.getMessage());
}
});
This uses the Guava ListenableFuture interface to process the response from Twilio on a different thread.
这使用Guava的ListenableFuture接口,在不同的线程上处理来自Twilio的响应。
6. Conclusion
6.结语
In this article, we learned how to send SMS and MMS using Twilio and Java.
在这篇文章中,我们学习了如何使用Twilio和Java发送短信和彩信。
While TwiML is the basis of all messages to and from Twilio servers, the Twilio Java client makes sending messages incredibly easy.
虽然TwiML是所有往来于Twilio服务器的信息的基础,但Twilio的Java客户端让信息的发送变得异常简单。
And, as always, the full codebase for this example can be found in our GitHub repository.
而且,像往常一样,这个例子的完整代码库可以在我们的GitHub 仓库中找到。