[Quick Start Series] Super Simple Tutorial for Sending Test SMS Using Alibaba Cloud

[Quick Start Series] Super Simple Tutorial for Sending Test SMS Using Alibaba Cloud

step

1. Alibaba Cloud configuration

1. Enter Alibaba Cloud homepage and click SMS service

Please add a picture description

2. SMS service interface

Please add a picture description

3. Click 快速学习, and then bind the test mobile phone number, click to call after bindingAPI发送短信

Please add a picture description

4. You can see some parameter settings on the left, and the demo code that can be selected on the right

Please add a picture description

5. What needs to be changed in the test code is your own accessKeyIdandaccessKeySecret

Click your account in the upper right corner of the SMS service page or homepage, and then clickAccessKeyId管理

Please add a picture description

click 创建AccessKey, then click查看Secret

Please add a picture description

You can see that there are AccessKey IDand above AccessKey Secret, and the content of these two parameters must be copied, and they will be used later (you need to verify the mobile phone number again to view the existing ones)

So far the configuration of the website is complete

Two, the code

1. Configure maven dependencies: pom.xml

<!-- 阿里云短信服务 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>2.0.22</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>darabonba-java-core</artifactId>
    <version>0.1.5-beta</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-dysmsapi20170525</artifactId>
    <version>1.0.1</version>
</dependency>
<!-- 运行时可能会发生缺少slf4j的错误,虽然不一定,但是尽量导一下比较好 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.7.2</version>
</dependency>

2. The upgraded SDK version is used here. Although the official website has codes, let’s stick it here

In these two demos, only two parameters need to be changed: the one we saved above AccessKey IDandAccessKey Secret

Tips: In these two demos, only these two parameters and the mobile phone number can be changed (that is, the format is ----------XXXX----------)

Java (asynchronous) demo

// This file is auto-generated, don't edit it. Thanks.
package com.r.demo;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;

public class SendSms {
    
    
    public static void main(String[] args) throws Exception {
    
    

        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("----------在这里写上自己的accessKeyId即可----------")
                .accessKeySecret("----------在这里写上自己的accessKeySecret即可----------")
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers("----------这里是你自己的手机号----------")
                .templateParam("{\"code\":\"1234\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }

}
operation result

Please add a picture description

I won't cut it if it's too long

direct result

{“headers”:{“Access-Control-Allow-Origin”:“*”,“x-acs-request-id”:“50F579AA-A36C-547C-9887-C9B597DBC519”,“Connection”:“keep-alive”,“Content-Length”:“110”,“Date”:“Sat, 29 Oct 2022 15:05:40 GMT”,“Content-Type”:“application/json;charset\u003dutf-8”,“x-acs-trace-id”:“2ca803d78068d3d55a936b22b44c5c68”},“body”:{“bizId”:“755622367055939907^0”,“code”:“OK”,“message”:“OK”,“requestId”:“50F579AA-A36C-547C-9887-C9B597DBC519”}}

Java demo

// This file is auto-generated, don't edit it. Thanks.
package com.r.demo;

import com.aliyun.tea.*;

public class Sample {
    
    

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
    
    
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args_) throws Exception {
    
    
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = Sample.createClient("----------在这里写上自己的accessKeyId即可----------", "----------在这里写上自己的accessKeySecret即可----------");
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers("----------这里是你自己的手机号----------")
                .setTemplateParam("{\"code\":\"1234\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
    
    
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            
            //这里我自己写了一个打印,要不然默认给的demo是不输出任何东西的,要不是收到短信了我还以为运行没反应呢。。。
            System.out.println("------------短信发送成功-------------");
            System.out.println("发送的手机号:" + sendSmsRequest.getPhoneNumbers() + "\n" +
                    "信息内容:" + sendSmsRequest.getTemplateParam());
            
        } catch (TeaException error) {
    
    
            // 如有需要,请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
    
    
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要,请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}
operation result

Please add a picture description

text message received by mobile phone

Please add a picture description

Guess you like

Origin blog.csdn.net/weixin_55452293/article/details/127920881