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

打印 上一主题 下一主题

主题 831|帖子 831|积分 2493

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

步骤

一、阿里云设置

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

2、短信服务界面

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

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

5、测试代码中必要改的是你自己的accessKeyId和accessKeySecret
在短信服务页面或主页的右上角点击自己的账号,然后点击AccessKeyId管理

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

可以看到上面有AccessKey ID和AccessKey Secret,这两个参数内容都要复制下来,都是一会要用到的(查看已有的必要手机号再次验证)
至此网站的设置完成
二、代码

1、设置maven依靠:pom.xml
  1. <!-- 阿里云短信服务 -->
  2. <dependency>
  3.     <groupId>com.aliyun</groupId>
  4.     <artifactId>dysmsapi20170525</artifactId>
  5.     <version>2.0.22</version>
  6. </dependency>
  7. <dependency>
  8.     <groupId>com.aliyun</groupId>
  9.     <artifactId>darabonba-java-core</artifactId>
  10.     <version>0.1.5-beta</version>
  11. </dependency>
  12. <dependency>
  13.     <groupId>com.aliyun</groupId>
  14.     <artifactId>alibabacloud-dysmsapi20170525</artifactId>
  15.     <version>1.0.1</version>
  16. </dependency>
  17. <!-- 运行时可能会发生缺少slf4j的错误,虽然不一定,但是尽量导一下比较好 -->
  18. <dependency>
  19.     <groupId>org.slf4j</groupId>
  20.     <artifactId>slf4j-nop</artifactId>
  21.     <version>1.7.2</version>
  22. </dependency>
复制代码
2、这里用的是升级版的SDK版本,虽然官网都有代码了,照旧在这里粘一下
   在这两个demo里面都只必要改两个参数:就是我们上面生存的那个AccessKey ID和AccessKey Secret
    tips:这两个demo里面只改这两个参数和手机号即可(就是格式为----------XXXX----------的这种)
  Java(异步)demo

  1. // This file is auto-generated, don't edit it. Thanks.
  2. package com.r.demo;
  3. import com.aliyun.auth.credentials.Credential;
  4. import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
  5. import com.aliyun.core.http.HttpClient;
  6. import com.aliyun.core.http.HttpMethod;
  7. import com.aliyun.core.http.ProxyOptions;
  8. import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
  9. import com.aliyun.sdk.service.dysmsapi20170525.models.*;
  10. import com.aliyun.sdk.service.dysmsapi20170525.*;
  11. import com.google.gson.Gson;
  12. import darabonba.core.RequestConfiguration;
  13. import darabonba.core.client.ClientOverrideConfiguration;
  14. import darabonba.core.utils.CommonUtil;
  15. import darabonba.core.TeaPair;
  16. //import javax.net.ssl.KeyManager;
  17. //import javax.net.ssl.X509TrustManager;
  18. import java.net.InetSocketAddress;
  19. import java.time.Duration;
  20. import java.util.*;
  21. import java.util.concurrent.CompletableFuture;
  22. public class SendSms {
  23.     public static void main(String[] args) throws Exception {
  24.         // HttpClient Configuration
  25.         /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
  26.                 .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
  27.                 .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
  28.                 .maxConnections(128) // Set the connection pool size
  29.                 .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
  30.                 // Configure the proxy
  31.                 .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
  32.                         .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
  33.                 // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
  34.                 .x509TrustManagers(new X509TrustManager[]{})
  35.                 .keyManagers(new KeyManager[]{})
  36.                 .ignoreSSL(false)
  37.                 .build();*/
  38.         // Configure Credentials authentication information, including ak, secret, token
  39.         StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
  40.                 .accessKeyId("----------在这里写上自己的accessKeyId即可----------")
  41.                 .accessKeySecret("----------在这里写上自己的accessKeySecret即可----------")
  42.                 //.securityToken("<your-token>") // use STS token
  43.                 .build());
  44.         // Configure the Client
  45.         AsyncClient client = AsyncClient.builder()
  46.                 .region("cn-hangzhou") // Region ID
  47.                 //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
  48.                 .credentialsProvider(provider)
  49.                 //.serviceConfiguration(Configuration.create()) // Service-level configuration
  50.                 // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
  51.                 .overrideConfiguration(
  52.                         ClientOverrideConfiguration.create()
  53.                                 .setEndpointOverride("dysmsapi.aliyuncs.com")
  54.                         //.setConnectTimeout(Duration.ofSeconds(30))
  55.                 )
  56.                 .build();
  57.         // Parameter settings for API request
  58.         SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
  59.                 .signName("阿里云短信测试")
  60.                 .templateCode("SMS_154950909")
  61.                 .phoneNumbers("----------这里是你自己的手机号----------")
  62.                 .templateParam("{"code":"1234"}")
  63.                 // Request-level configuration rewrite, can set Http request parameters, etc.
  64.                 // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
  65.                 .build();
  66.         // Asynchronously get the return value of the API request
  67.         CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
  68.         // Synchronously get the return value of the API request
  69.         SendSmsResponse resp = response.get();
  70.         System.out.println(new Gson().toJson(resp));
  71.         // Asynchronous processing of return values
  72.         /*response.thenAccept(resp -> {
  73.             System.out.println(new Gson().toJson(resp));
  74.         }).exceptionally(throwable -> { // Handling exceptions
  75.             System.out.println(throwable.getMessage());
  76.             return null;
  77.         });*/
  78.         // Finally, close the client
  79.         client.close();
  80.     }
  81. }
复制代码
运行结果


太长了就不截了
直接结果
   {“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

  1. // This file is auto-generated, don't edit it. Thanks.
  2. package com.r.demo;
  3. import com.aliyun.tea.*;
  4. public class Sample {
  5.     /**
  6.      * 使用AK&SK初始化账号Client
  7.      * @param accessKeyId
  8.      * @param accessKeySecret
  9.      * @return Client
  10.      * @throws Exception
  11.      */
  12.     public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
  13.         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
  14.                 // 您的 AccessKey ID
  15.                 .setAccessKeyId(accessKeyId)
  16.                 // 您的 AccessKey Secret
  17.                 .setAccessKeySecret(accessKeySecret);
  18.         // 访问的域名
  19.         config.endpoint = "dysmsapi.aliyuncs.com";
  20.         return new com.aliyun.dysmsapi20170525.Client(config);
  21.     }
  22.     public static void main(String[] args_) throws Exception {
  23.         java.util.List<String> args = java.util.Arrays.asList(args_);
  24.         com.aliyun.dysmsapi20170525.Client client = Sample.createClient("----------在这里写上自己的accessKeyId即可----------", "----------在这里写上自己的accessKeySecret即可----------");
  25.         com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
  26.                 .setSignName("阿里云短信测试")
  27.                 .setTemplateCode("SMS_154950909")
  28.                 .setPhoneNumbers("----------这里是你自己的手机号----------")
  29.                 .setTemplateParam("{"code":"1234"}");
  30.         com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
  31.         try {
  32.             // 复制代码运行请自行打印 API 的返回值
  33.             client.sendSmsWithOptions(sendSmsRequest, runtime);
  34.             
  35.             //这里我自己写了一个打印,要不然默认给的demo是不输出任何东西的,要不是收到短信了我还以为运行没反应呢。。。
  36.             System.out.println("------------短信发送成功-------------");
  37.             System.out.println("发送的手机号:" + sendSmsRequest.getPhoneNumbers() + "\n" +
  38.                     "信息内容:" + sendSmsRequest.getTemplateParam());
  39.             
  40.         } catch (TeaException error) {
  41.             // 如有需要,请打印 error
  42.             com.aliyun.teautil.Common.assertAsString(error.message);
  43.         } catch (Exception _error) {
  44.             TeaException error = new TeaException(_error.getMessage(), _error);
  45.             // 如有需要,请打印 error
  46.             com.aliyun.teautil.Common.assertAsString(error.message);
  47.         }
  48.     }
  49. }
复制代码
运行结果


手机收到的短信



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

徐锦洪

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表