java實現傳送簡訊功能
阿新 • • 發佈:2018-11-26
1、在阿里雲簡訊服務中添加簽名
2、在阿里雲簡訊服務中新增模板
3、建立屬於自己的AccessKey ID和Access Key Secret
4、需要下載兩個jar包
aliyun-java-sdk-core-3.3.1.jar
aliyun-java-sdk-dysmsapi-1.0.0.jar
5、然後新建Sendmss類(需要修改四個地方)
①:此處需要替換成開發者自己的AK(在阿里雲訪問控制檯尋找) static final String accessKeyId = "xxxxxxxxxx";
②: static final String accessKeySecret ="xxxxxxxxxxxxxxxxxxxx";
③:必填:簡訊簽名-可在簡訊控制檯中找到 request.setSignName("重慶洋世達");
④:可選:模板中的變數替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為 request.setTemplateParam("{ \"code\":\""+yzm+"\"}");
package com.zuxia.maven.carsystem.util; 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.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile;public class Sendmss { //產品名稱:雲通訊簡訊API產品,開發者無需替換 static final String product = "Dysmsapi"; //產品域名,開發者無需替換 static final String domain = "dysmsapi.aliyuncs.com"; // TODO 此處需要替換成開發者自己的AK(在阿里雲訪問控制檯尋找) static final String accessKeyId = "LTAI2ODlgGwI4FAv"; //LTAI2ODlgGwI4FAv LTAIzRTRlz9xojmi //Xj2HtQ4A3SMjoJtqwyIrdgFdWN0WMF xt5RtOIqDSkHUu734niABQlHagsCFc static final String accessKeySecret ="Xj2HtQ4A3SMjoJtqwyIrdgFdWN0WMF"; public SendSmsResponse sendSms(String phone,String yzm) throws ClientException { //可自助調整超時時間 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //初始化acsClient,暫不支援region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //組裝請求物件-具體描述見控制檯-文件部分內容 SendSmsRequest request = new SendSmsRequest(); //必填:待發送手機號 request.setPhoneNumbers(phone); //必填:簡訊簽名-可在簡訊控制檯中找到 request.setSignName("重慶洋世達"); //必填:簡訊模板-可在簡訊控制檯中找到 request.setTemplateCode("SMS_145500580"); //可選:模板中的變數替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為 request.setTemplateParam("{ \"code\":\""+yzm+"\"}"); //選填-上行簡訊擴充套件碼(無特殊需求使用者請忽略此欄位) //request.setSmsUpExtendCode("90997"); //可選:outId為提供給業務方擴充套件欄位,最終在簡訊回執訊息中將此值帶回給呼叫者 request.setOutId("yourOutId"); //hint 此處可能會丟擲異常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); return sendSmsResponse; } }
新建test類
package com.zuxia.maven.carsystem.test; import com.aliyuncs.exceptions.ClientException; import com.zuxia.maven.carsystem.util.Sendmss; public class Test { public static void main(String[] args) { Sendmss s = new Sendmss(); String phone = "15949345955"; String yzm = "123456"; try { s.sendSms(phone, yzm); } catch (ClientException e) { System.out.println(e.getMessage()); e.printStackTrace(); } System.out.println("傳送成功!"); } }