【快速上手系列】使用阿里云发送测试短信超简单教程
创始人
2024-01-29 23:26:35
0

【快速上手系列】使用阿里云发送测试短信超简单教程

步骤

一、阿里云配置

1、进入阿里云首页点击短信服务

请添加图片描述

2、短信服务界面

请添加图片描述

3、点击快速学习,然后绑定测试手机号,绑定好后点击调用API发送短信

请添加图片描述

4、左侧可以看到一些参数设置,右面是可以选择的demo代码

请添加图片描述

5、测试代码中需要改的是你自己的accessKeyIdaccessKeySecret

在短信服务页面或主页的右上角点击自己的账号,然后点击AccessKeyId管理

请添加图片描述

点击创建AccessKey,然后点击查看Secret

请添加图片描述

可以看到上面有AccessKey IDAccessKey Secret,这两个参数内容都要复制下来,都是一会要用到的(查看已有的需要手机号再次验证)

至此网站的配置完成

二、代码

1、配置maven依赖:pom.xml


com.aliyundysmsapi201705252.0.22

com.aliyundarabonba-java-core0.1.5-beta

com.aliyunalibabacloud-dysmsapi201705251.0.1


org.slf4jslf4j-nop1.7.2

2、这里用的是升级版的SDK版本,虽然官网都有代码了,还是在这里粘一下

在这两个demo里面都只需要改两个参数:就是我们上面保存的那个AccessKey IDAccessKey Secret

tips:这两个demo里面只改这两个参数和手机号即可(就是格式为----------XXXX----------的这种)

Java(异步)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("", 9001)).setCredentials("", ""))// 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, tokenStaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder().accessKeyId("----------在这里写上自己的accessKeyId即可----------").accessKeySecret("----------在这里写上自己的accessKeySecret即可----------")//.securityToken("") // use STS token.build());// Configure the ClientAsyncClient 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 requestSendSmsRequest 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 requestCompletableFuture response = client.sendSms(sendSmsRequest);// Synchronously get the return value of the API requestSendSmsResponse 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 exceptionsSystem.out.println(throwable.getMessage());return null;});*/// Finally, close the clientclient.close();}}
运行结果

请添加图片描述

太长了就不截了

直接结果

{“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 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) {// 如有需要,请打印 errorcom.aliyun.teautil.Common.assertAsString(error.message);} catch (Exception _error) {TeaException error = new TeaException(_error.getMessage(), _error);// 如有需要,请打印 errorcom.aliyun.teautil.Common.assertAsString(error.message);}}
}
运行结果

请添加图片描述

手机收到的短信

请添加图片描述

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
一帆风顺二龙腾飞三阳开泰祝福语... 本篇文章极速百科给大家谈谈一帆风顺二龙腾飞三阳开泰祝福语,以及一帆风顺二龙腾飞三阳开泰祝福语结婚对应...
美团联名卡审核成功待激活(美团... 今天百科达人给各位分享美团联名卡审核成功待激活的知识,其中也会对美团联名卡审核未通过进行解释,如果能...