阿里云短信工具类

一、实战版

  1. 导入依赖
        <!--阿里云短信测试服务-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibabacloud-dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>
  1. 代码

application.properties配置文件设置子用户密钥

# 配置发送短信用户密钥
aliyun.sms.accessKeyId=
aliyun.sms.secret=

读取配置初始化为静态常量

// 初始化,读取配置文件的用户密钥等
@Component
public class ConstantPropertiesUtils implements InitializingBean {
    
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.secret}")
    private String secret;

    public static String ACCESS_KEY_ID;
    public static String SECRECT;

    @Override
    public void afterPropertiesSet() throws Exception {
        ACCESS_KEY_ID=accessKeyId;
        SECRECT=secret;
    }
}

短信工具类调用

/**
 * 短信发送工具类
 */
@Slf4j
public class SMSUtils {

    /**
     * 封装一个方法来发送短信
     * @param phoneNumbers 手机号
     * @param param 参数
     */
    public static void sendMessage(String phoneNumbers,String param){

        // 1. 设置accessKeyId和accessKeySecret
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(SECRECT)
                .build());

        // 2. 新建一个异步的客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                // 客户端级配置重写,可以设置端点、Http请求参数等。
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        // 3. 使用建造者模式构建请求体对象,设置签名、电话的号码、模板、以及发送验证码的值
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers(phoneNumbers)
                .templateParam("{\"code\":\""+param+"\"}")
                .build();


        // 4. 异步获取 API 请求的返回值,响应后打印日志,查看是否发送成功
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        log.info("短信发送成功!返回响应体为"+response);

        // 5. 最后,关闭客户端
        client.close();
    }
}

二、官方版

  1. 导入依赖
        <!--阿里云短信测试服务-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibabacloud-dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>
  1. 代码
package 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配置
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // 设置连接超时时间,默认为10秒
                .responseTimeout(Duration.ofSeconds(10)) // 设置响应超时时间,默认为20秒
                .maxConnections(128) // 设置连接池大小
                .maxIdleTimeOut(Duration.ofSeconds(50)) // 设置连接池超时,默认为30秒
                // 配置代理
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // 如果是https连接,则需要配置证书,或者忽略证书(. gnreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // 配置凭据鉴别信息,包括ak、秘密、token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // 请确保设置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // 使用STS的token
                .build());

        // 配置客户端
        AsyncClient client = AsyncClient.builder()
                .region("undefined") // 地区ID
                //.httpClient(httpClient) // 使用配置的HttpClient,否则使用默认的HttpClient(Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // 服务级配置
                // 客户端级配置重写,可以设置Endpoint、Http请求参数等。
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // API请求的参数设置
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers("your_value")
                .signName("your_value")
                // 请求级配置重写,可以设置Http请求参数等。
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // 异步获取API请求的返回值
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 同步获取API请求的返回值
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // 返回值的异步处理
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // 处理异常
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // 最后,关闭客户端
        client.close();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一码一上午

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值