java中阿里云实现短信推送(亲测可用)

第一步先导入阿里云jar包

     
        <dependency>
		    <groupId>com.aliyun</groupId>
		    <artifactId>aliyun-java-sdk-core</artifactId>
		    <version>3.3.1</version>
		</dependency>
		<dependency>
		    <groupId>com.aliyun</groupId>
		    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
		    <version>1.0.0</version>
		</dependency>

直接上测试代码

import java.util.HashMap;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zdb.util.UserUtil;


public class Test {
	private static Logger log = LoggerFactory.getLogger(Test.class);
	
	public static void main(String[] args) {
		//签名【类似于公司名字】
		/**
		 * 类似于: 短信的格式
		 * 	【签名(signName)】内容(message)+一些模板内容
		 * 
		 * */
		String signName = UserUtil.getSignName();
		//#访问键(阿里云平台注册的)
		String accesskey= UserUtil.getAccessKey();
		//#访问秘钥(阿里云平台注册的)
		String accessSecret = UserUtil.getAccessSecret();
		
		System.out.println(signName);
		System.out.println(accesskey);
		System.out.println(accessSecret);
		//内容
		String message ="什么鬼";
		//电话号
		String phone = "1234567890";
		//推送的模板在(阿里云中申请的)
		String templateCode = "SMS_000";
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accesskey,accessSecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
			IAcsClient client = new DefaultAcsClient(profile);
			
			SendSmsRequest request = new SendSmsRequest(); 
			
			Map<String, String> map =new HashMap<String, String>();
			map.put("message", message);//消息
			
			request.setMethod(MethodType.POST);
			request.setPhoneNumbers(phone);	//接收号码
			request.setSignName(signName);;	//控制台创建的签名名称
			request.setTemplateCode(templateCode);;// 控制台创建的模板CODE
			request.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。"
			SendSmsResponse httpResponse = client.getAcsResponse(request);
			if("OK".equals(httpResponse.getCode())){
				System.out.println("success_消息发送成功");
			}else{
				if(log.isErrorEnabled()){
					log.error(httpResponse.getCode()+"  "+httpResponse.getMessage());
				}
				System.out.println("error_消息发送失败");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("error_消息发送失败");
		}
	}
}

这里面有几个需要在阿里上申请的  这个是模板模板CODE就是在以上代码中是templateCode,左边还有一个签名,签名必须签名管理里面审核过以上代码中是signName

还有一些数据 固定值

猜你喜欢

转载自blog.csdn.net/qq_38092788/article/details/82984660