Calling alicloud SMS service using Java

Calling alicloud SMS service using Java

The SMS verification code must be familiar to everyone. It is used in many websites and apps. Such as login, registration, identity verification and other scenarios. However, generally, SMS services are outsourced to third-party companies. Next, I will share with you how to use Alibaba's SMS services.

Log in to Alibaba cloud to apply for SMS service

First, let's log in Alibaba cloud official website , search SMS service, register and open authorization.
Here, you can also click the portal below to facilitate the quick application of small partners.
Alibaba cloud SMS service

Request signature and template

Select domestic message or international message according to the region receiving SMS, and apply for corresponding signature and template. There is nothing to pay attention to when applying for a signature. Alibaba cloud has a comment prompt. After applying for a signature application template, the template name is the prefix of the received message;
Template content: you can write it yourself or view the template library for user-defined modification;
Application Description: personal learning exchange. (the first scribble failed)
The information is usually passed in less than half an hour after it is filled in. I have to admire Alibaba cloud for its efficiency.

Apply for an AccessKey to obtain the control permission of an alicloud account

For security reasons, it is recommended to use the sub-user AccessKey with the minimum corresponding permission.

Please remember not to close the window immediately after applying for the sub-user AccessKey. Save the applied AccessKeySecret first, because after closing, you can no longer view the AccessKeySecret, but only the AccessKeyId.

Test SMS sending

After the preparation is completed, in the quick learning bar of the SMS service, you can use the created signature and template to send the test to see the effect. When there is no problem, you can conduct coding control. (if the balance is insufficient, you need to recharge the account first) don't panic when encountering the error code, and check the help document first;

best practice

Calling alicloud SMS service using Java

Here, try to use the new api for manipulation. Link: Official documents
Maven project supports the following packages:

<!--Alibaba cloud SMS sdk-->

Tools are as follows:

package com.Utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

 * @ClassName AliyunSmsUtils
 * @Description AliyunSmsUtils
 * @Author Wang
 * @Date 2020/7/4 11:14
 * @Version 1.0
public class AliyunSmsUtils {
    //Product Name: cloud communication SMS API product, developers do not need to replace it
    static final String product = "Dysmsapi";
    //Product domain name, developers do not need to replace
    static final String domain = "";

    // TODO needs to be replaced with the developer's own AK (look for it on the Alibaba cloud access console)
    static final String accessKeyId = "your accessKeyId";
    static final String accessKeySecret = "your accessKeySecret";

    public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {
        //Self adjustable timeout
        System.setProperty("", "10000");
        System.setProperty("", "10000");
        //Initialize acsClient. Regionization is not supported for the time being
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //Assembly request object - see console - document for details
        SendSmsRequest request = new SendSmsRequest();
        //Required: mobile number to be sent
        //Required: SMS signature - can be found in SMS console
        request.setSignName("Signature name");
        //Required: SMS template - can be found in SMS console
        request.setTemplateCode("SMS_Code");//SMS_ Template Code at the beginning
        //Optional: the variables in the template replace the JSON string. For example, when the template content is "dear ${name}, and your verification code is ${code}", the value here is
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        //Optional - uplink SMS extension code (please ignore this field for users without special needs)
        //Optional: outId is the extension field provided to the business party. Finally, this value will be brought back to the caller in the SMS receipt message
        //  request.setOutId("yourOutId");
        //hint exceptions may be thrown here. Pay attention to catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            System.out.println("SMS sent successfully!");
        } else {
            System.out.println("SMS sending failed!");
        return sendSmsResponse;

Random generation of verification code

   private static int newcode;

    public static int getNewcode() {
        return newcode;

    public static void setNewcode() {
        newcode = (int) (Math.random() * 9999) + 100;  //Each call generates a four digit random number

Test Main method

  public static void main(String[] args) throws ClientException{
        String code = Integer.toString(getNewcode());
        System.out.println("The verification code sent is:" + code);
        //Send SMS
        SendSmsResponse response = sendSms("yourPhone", code); //
        System.out.println("Data returned by SMS interface----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        // System.out.println("BizId=" + response.getBizId());

Test successful

Tags: Java Maven IDEA RESTful Alibaba Cloud

Posted by lordvader on Wed, 01 Jun 2022 00:44:47 +0530