All Products
Search
Document Center

Short Message Service:Use SMS SDK for Java

Last Updated:Nov 18, 2024

This topic describes how to use SMS SDK for Java and OpenAPI Explorer to send a message to a mobile number.

Step 1: View the API references

Before you call an API operation, we recommend that you learn about the related parameters and permissions. For more information, see SendMessageToGlobe and List of operations by function.

Step 2: Create a RAM user and grant permissions to the RAM user

Important

We recommend that you grant permissions to a RAM user and use the RAM user to make API calls and perform daily O&M. For information about RAM users, see Overview of RAM users.

Create a RAM user

Go to the Create User page of the Resource Access Management (RAM) console, specify a RAM username, set the Access Mode parameter to OpenAPI Access, and then click OK. Record the AccessKey information.

Grant permissions to the RAM user

Go to the Users page of the RAM console, find the RAM user, and click Add Permissions in the Actions column. In the Policy section of the panel that appears, search for and select the AliyunDysmsFullAccess policy, and then click Grant permissions.

Note
  • AliyunDysmsFullAccess: specifies the management permissions on SMS.

  • AliyunDysmsReadOnlyAccess: specifies the read-only permissions on SMS.

For more information about how to create a custom policy, see RAM authorization.

Step 3: Call an API operation

SDKs can be easily integrated into your application and cover the widest range of operations. We recommend that you use SDKs to call API operations. In this topic, SMS SDK for Java is used to call an API operation. You can also use SMS SDK for another language. For more information, visit SDK Center.

Preparations

  • Check whether the Java version is later than Java 8. For information about how to deploy a Java environment, see Build a Java development environment on Windows.

  • Configure Maven dependencies and install the SDK.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>dysmsapi20180501</artifactId>
        <version>1.0.8</version>
    </dependency>
  • Configure environment variables to read AccessKey pair information. For information about how to configure environment variables, see Configure environment variables in Linux, macOS, and Windows.

    Note

    To prevent the AccessKey pair from being leaked due to hard-coding, you must configure environment variables to obtain an AccessKey pair.

    In this example, the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are used.

Sample code

The following sample code shows how to use the SDK to call an API operation to send a message. Specify the parameters based on the annotations.

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 environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is configured. 
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey secret. Make sure that the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is configured. 
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

        // Configure the endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new Client(config);
    }

    public static void main(String[] args) throws Exception {
        // Initialize the client
        Client client = Sample.createClient();

        // Construct the request object and specify the request parameters
        SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
                .setTo("<YOUR_VALUE>")
                .setMessage("<YOUR_VALUE>");

        // Obtain the response object
        SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);

        // Response body and headers
        System.out.println(toJSONString(sendSmsResponse));
    }
}

You can also download the sample code that OpenAPI Explorer provides and execute it directly.

Download sample code

  1. Visit OpenAPI Explorer.

  2. On the Parameters tab, configure the request parameters.

    • Sample value of the To parameter: 88691567****

    • Sample value of the Message parameter: This is a test message.

  3. On the SDK Sample Code tab, select v2.0 for SDK Version and Java for Language. Click Download Project to download the sample code package.

  4. Load the project by using IDE. After the dependencies are loaded, open the Sample.java file in the src/main/java/com/aliyun/sample/Sample.java directory.

Run the project

Sample output:

{
  "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"
  }
}