阿里发送短信

441 阅读1分钟

开发步骤

1.开通短信服务 拿到key secret

2.配置短信模板 公司名字 变量字段 //比如初始登陆密码或验证码

3.代码 添加依赖jar包 //maven 实现 //可以参考官方demo,直接拿来用

4.测试发送短信 //成功

源码

package com.wz.bpm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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;

/**
 * 发送短信
 * @author gongzhihao
 *
 */
public class SmsUtil {
	private static Logger logger = LoggerFactory.getLogger(SmsUtil.class);
	
	/**
	 * 
	 * @param phone
	 * @param password
	 */
	public static void sendSms(String phone,String password) {
		logger.info("phone=" + phone + ",password=" + password );
		DefaultProfile profile = DefaultProfile.getProfile("default", "key", "secret"); //配置key和secret
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        
        request.putQueryParameter("RegionId", "default");
        
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "XXX");
        request.putQueryParameter("TemplateCode", "XXX");
        
        String var = "{\"code\":" + password + "}"; //code是短信模板里的参数字段,在这里填写的就是具体的值
        request.putQueryParameter("TemplateParam", var);
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info(response.getData());
        } catch (ServerException e) {
            logger.error("服务器异常:", e);
        } catch (ClientException e) {
        	logger.error("客户端异常:", e);
        }
	}
}

参考

官方文档https://help.aliyun.com/document_detail/112148.html?spm=a2c4g.11186623.6.646.74b460e2Cgp0k1

官方在线测试demo api.aliyun.com/?spm=a2c4g.…}&tab=MOCK&lang=JAVA


其他文章 yq.aliyun.com/articles/59…