Java實現(xiàn)阿里云短信接口的示例
阿里云短信服務接口
阿里云短信服務(Short Message Service)是阿里云為用戶提供的一種通信服務的能力。
支持向國內(nèi)和國際快速發(fā)送驗證碼、短信通知和推廣短信,服務范圍覆蓋全球200多個國家和地區(qū)。國內(nèi)短信支持三網(wǎng)合一專屬通道,與工信部攜號轉(zhuǎn)網(wǎng)平臺實時互聯(lián)。電信級運維保障,實時監(jiān)控自動切換,到達率高達99%。完美支撐雙11期間20億短信發(fā)送,6億用戶觸達。
快速開發(fā)
①開啟短信服務
1)登陸阿里云服務平臺
2)選擇控制臺
3)點擊左上角下拉按鈕選擇短信服務
4)開通短信服務
②實名認證
1)如果沒有實名認證需要跳轉(zhuǎn)實名認證界面
2)選擇相應的認證
3)選擇支付寶快速的認證
③創(chuàng)建簽名與模板
1)添加簽名
2)選擇簽名使用場景
驗證碼:只能使用驗證碼模板
通用:都可以使用(申請較為嚴格)
3)創(chuàng)建短信模板
4)根據(jù)常用模板庫申請相應短信模板
根據(jù)使用簽名可以創(chuàng)建相應模板,注意:驗證碼簽名只能使用驗證碼模板
④完成前期的準備工作
1)獲取申請成功的簽名(注冊時的簽名名稱)
2)獲取申請成功的短信模板(模版code)
3)獲取AccessKey ID 和 AccessKey Secret
⑤代碼書寫
1)導入相應坐標
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency>
2)創(chuàng)建短信發(fā)送工具類
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 SendSms { private static final String AccessKeyId = '';//你的accessKeyId private static final String AccessKeySecret = '';//你的accessKeySecret private static final String SignName = '';//使用的簽名 private static final String TemplateCode = '';//發(fā)送短信使用的模板 private static IAcsClient acs = null;//服務對象 private static SendSmsRequest req = new SendSmsRequest();//短信發(fā)送請求對象 static { IClientProfile profile = DefaultProfile.getProfile('cn-hangzhou', AccessKeyId, AccessKeySecret); acs = new DefaultAcsClient(profile); } //隨機生成指定位數(shù)驗證碼 public static StringBuffer randomCode(int number){ //驗證碼內(nèi)容集 final char[] CHARS = {’0’, ’1’, ’2’, ’3’, ’4’, ’5’, ’6’, ’7’, ’8’, ’9’}; StringBuffer stringBuffer=new StringBuffer(); Random r=new Random(); for(int i=0;i<number;i++){ stringBuffer.append(CHARS[r.nextInt(CHARS.length)]); } return stringBuffer; } //自定義發(fā)送方法 public static boolean sendCode(String mobile, String code) throws ClientException { req.setPhoneNumbers(mobile);//設置接收短信手機號 req.setSignName(SignName);//設置使用簽名 req.setTemplateCode(TemplateCode);//設置使用通知模板id req.setTemplateParam('{'code':'' + code + ''}');//設置請求參數(shù) 以json字符串形式與模板一致 SendSmsResponse res = acs.getAcsResponse(req);//向服務器發(fā)送請求 //System.out.println('res code: ' + res.getCode());//響應狀態(tài)碼 // System.out.println('res message: ' + res.getMessage());//響應信息 if (res.getCode() == null && !res.getCode().equals('OK')) { System.out.println(res.getMessage()); return false; } return true; } public static void main(String[] args) throws ClientException { System.out.println(sendCode('手機號','驗證碼')); }}
更多請查看阿里短信服務手冊阿里短信服務手冊
到此這篇關于Java實現(xiàn)阿里云短信接口的示例的文章就介紹到這了,更多相關Java 阿里云短信接口內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
