The Alibaba Cloud Short Message Service (SMS) SDK for Java is the official SDK for calling SMS API operations.
Installation
System requirements
Java version: Make sure that your Java version is Java 8 or later. For information about how to configure the Java environment, see Set up a Java development environment on Windows.
Operating system: Windows, Linux, or macOS. No special requirements apply.
Other dependencies: Maven 3.0 or later to build the project.
Install using Maven
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20180501</artifactId>
<!-- Replace 'the-latest-version' with the latest version from https://mvnrepository.com/artifact/com.aliyun/dysmsapi20180501 -->
<version>the-latest-version</version>
</dependency>Authentication configuration
Step 1: Create a RAM user and grant permissions
Your Alibaba Cloud account has extensive permissions. We recommend that you use a Resource Access Management (RAM) user to call API operations and perform daily operations and maintenance (O&M). For more information about RAM users, see Overview of RAM users.
Create a RAM user: Go to the Create User page, configure the user information, set Access Mode to Programmatic Access, and then click OK to create the RAM user. Save the AccessKey information.
Grant permissions to the RAM user: Go to the User List page and find the RAM user that you created. Click Add Permissions in the Actions column. In the Policy text search box, enter AliyunDysmsFullAccess. Select this policy and click OK to grant the permissions.
NoteAliyunDysmsFullAccess: Grants full management permissions for SMS.
AliyunDysmsReadOnlyAccess: Grants read-only permissions for SMS.
To create a custom policy, see Authorization information.
Step 2: Obtain access credentials
Configure environment variables to retrieve your AccessKey pair. For information about how to configure environment variables, see Configure environment variables in Linux, macOS, and Windows.
To prevent your AccessKey pair from being leaked, do not hard-code it in your code. Instead, retrieve your AccessKey pair by configuring environment variables.
The code examples in this topic use
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETas the environment variable names.
Security best practices
Store credentials using environment variables or Key Management Service (KMS).
Rotate your AccessKey pairs periodically.
Follow the principle of least privilege and grant RAM users only the minimum required permissions.
Do not print credential information in logs.
In a production environment, use RAM roles instead of Alibaba Cloud account credentials.
Getting started
Code example
The following sample code shows how to call the API operation to send a text message. Configure the parameters based on the comments in the code.
package com.aliyun.sample;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeResponse;
import static com.aliyun.teautil.Common.toJSONString;
public class Sample {
public static Client createClient() throws Exception {
Config config = new Config()
// Configure the AccessKey ID. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Configure the AccessKey secret. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Configure the endpoint.
config.endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args) throws Exception {
// Initialize the request client.
Client client = Sample.createClient();
// Create a request object and set the parameter values.
SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
.setTo("<YOUR_VALUE>")
.setMessage("<YOUR_VALUE>");
// Obtain the response object.
SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);
// The response includes the body and headers from the server.
System.out.println(toJSONString(sendSmsResponse));
}
}Download the sample code
You can also download the sample code and run it directly.
Go to SendMessageToGlobe.
On the Parameter Settings tab on the left, specify the required parameters. For example:
To: 88691567****
Message: This is a test message.
On the SDK Sample tab on the right, set SDK Version to v2.0, select Java for Language (you can select the Java or Java asynchronous option), and then click Download Complete Project to download the sample code package.
Decompress the package and open the project in your IDE. After the dependencies are loaded, open the
src/main/java/com/aliyun/sample/Sample.javafile.
Run the project
After you run the project, the following output is returned:
{
"headers": {
"date": "Tue, 24 Oct 2023 07:47:17 GMT",
"content-type": "application/json;charset=utf-8",
"content-length": "263",
"connection": "keep-alive",
"keep-alive": "timeout=25",
"access-control-allow-origin": "*",
"access-control-expose-headers": "*",
"x-acs-request-id": "97B1D7B6-F2F6-3A50-97BC-A90B43EC962F",
"x-acs-trace-id": "29c11fe4c778b74774d5f5602f0e7975",
"etag": "2a+mcDRTDkXqx9VF7b6U57Q3"
},
"statusCode": 200,
"body": {
"ResponseCode": "OK",
"NumberDetail": {
"Region": "Taiwan",
"Country": "Taiwan, Province of China",
"Carrier": "FarEasTone"
},
"RequestId": "97B1D7B6-F2F6-3A50-97BC-A90B43EC962F",
"Segments": "1",
"ResponseDescription": "OK",
"To": "88691567****",
"MessageId": "191921698133637273"
}
}Summary of best practices
Performance optimization
Use a connection pool to reuse HTTP connections and reduce connection setup overhead.
For high-frequency calls, consider using an asynchronous invocation pattern.
Set appropriate timeout periods to prevent long waits that can affect service performance.
When you perform batch operations, use the batch processing capabilities of the API.
Security recommendations
Always use the HTTPS protocol to communicate with the API.
Do not record sensitive information, such as phone numbers and verification codes, in logs.
Validate the format of user-provided phone numbers to prevent malicious input.
Use temporary credentials from Alibaba Cloud Security Token Service (STS) instead of long-term credentials.
Resource management
Promptly close client connections that are no longer in use.
If you have many concurrent requests, configure an appropriate thread pool size.
Monitor the API call frequency to avoid exceeding the queries-per-second (QPS) limit.
References
GitHub repositories:
Review OpenAPI documentation:
Before you call an API operation, read the corresponding documentation to learn about the required parameters, permissions, and other details. For this example, see SendMessageToGlobe. For more information, see API overview.
Call an API operation:
Using an SDK is the recommended method for calling API operations. This topic uses the Java SDK as an example. The process is similar for other languages. For more information, see Short Message Service SDK.