Java教程

阿里云的短信服务acsClient+java

本文主要是介绍阿里云的短信服务acsClient+java,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 开通aliyun上的短信服务,主要得到

(1)访问秘钥 accessKeyId <==>AccessKeySecret
(2)短信签名+模板code
参考官方文档

2. API测试短信发送:

参考官方文档
(1)下载sdk (原版)

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.3</version>
        </dependency>

(2) 测试

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.16</version>
</dependency>
*/
    public  void sendSms( ) {
        // 1. 初始化acsClient
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); 
        IAcsClient client = new DefaultAcsClient(profile);
        // 2. 组装请求对象
        /***
       http(s)://dysmsapi.aliyuncs.com/?Action=SendSms
	   &PhoneNumbers=1381111*****
       &SignName=阿里云
       &TemplateCode=SMS_1530****
       &<公共请求参数>
		***/
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");  // url
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        /*****/
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);   // 待发送手机号
        request.putQueryParameter("SignName", "aliyun");  // 短信签名
        request.putQueryParameter("TemplateCode", "SMS_200191424"); // 短信模板code
        /**填充短信模板**/
        Map<String, String> params = new HashMap<>();
        params.put("station", "station");
        params.put("channel", "channel");
        params.put("alarm", "alarm");
        params.put("message", "message");
        request.putQueryParameter("TemplateParam", JSON.toJSONString(params)); // 短信模板变量对应的实际值
       	// 3. 发送请求
        try {
            CommonResponse response = client.getCommonResponse(request); 
            log.info(response.getData());
        } catch (Exception e) {
            log.error("短信发送失败:", e);
        }
    }
这篇关于阿里云的短信服务acsClient+java的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!