调用腾讯API发短信

2022/7/12 23:31:38

本文主要是介绍调用腾讯API发短信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、导入pom依赖:

<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
    <!-- 请到https://search.maven.org/search?q=tencentcloud-sdk-java查询最新版本 -->
    <version>3.0.112</version>
</dependency>

2、代码
public static String sendSMS(){
        String result = "";
        // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,见《创建secretId和secretKey》小节
        Credential cred = new Credential("XXX",
                "XXX");

        // 实例化要请求产品(以cvm为例)的client对象
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);
        SmsClient smsClient = new SmsClient(cred, "ap-chongqing");//第二个ap-chongqing 填产品所在的区
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppid("1111");//appId ,见《创建应用》小节
        String[] phones={"+8613822222222"};  //发送短信的目标手机号,可填多个。
        sendSmsRequest.setPhoneNumberSet(phones);
        sendSmsRequest.setTemplateID("333333");  //模版id,见《创建短信签名和模版》小节
        String [] templateParam={getCode()};//模版参数,从前往后对应的是模版的{1}、{2}等,见《创建短信签名和模版》小节
        sendSmsRequest.setTemplateParamSet(templateParam);
        sendSmsRequest.setSign("哈哈哈"); //签名内容,不是填签名id,见《创建短信签名和模版》小节
        try {
            SendSmsResponse sendSmsResponse= smsClient.SendSms(sendSmsRequest); //发送短信
            SendStatus[] status = sendSmsResponse.getSendStatusSet();
            for (SendStatus st : status) {
                if(st.getCode().equalsIgnoreCase("Ok")){
                    result = st.getCode();
                } else {
                    result = st.getMessage();
                }
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return result;
    }

 




这篇关于调用腾讯API发短信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程