阿里云短信工具类

一、实战版

  1. 导入依赖
        
        <dependency>
            <groupId>com.aliyungroupId>
            <artifactId>alibabacloud-dysmsapi20170525artifactId>
            <version>2.0.23version>
        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.aliyungroupId>
            <artifactId>alibabacloud-dysmsapi20170525artifactId>
            <version>2.0.23version>
        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("", 9001))
                        .setCredentials("", ""))
                // 如果是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();
    }
}

你可能感兴趣的:(文章,阿里云,java,ssl)