java中阿里短信服務(短信驗證碼)
1. 創建簽名
- 如下位置創建簽名,等待審覈通過
2. 創建模板
- 如下位置創建模板,等待審覈通過
3. 測試驗證碼功能
- 填寫相關信息,測試發送
注:發送失敗可能因爲你餘額不足。可以選擇購買套餐。新號可去嘗試下圖位置領取免費短信。
- 官網主頁下拉最後
4. 查看Api Demo
5. 獲取AK信息
- 創建AccessKey
- 保存一下AccessKeyId和AccessKeySecret
- 將其複製分別填到AccessKeyId和AccessKeySecret的位置
6. 複製Api Demo到eclipse;複製依賴到pom.xml
7.自建工具類
//六位隨機密碼生成
//傳入手機號,成功返回後臺隨機驗證碼,失敗返回null
public class ToolNote {
public static String getNote(String tel){
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的accesskeyId", "你的secret");
IAcsClient client = new DefaultAcsClient(profile);
String[] codees={"0","1","2","3","4","5","6","7","8","9"};
String code="";
for(int i=0;i<6;i++){
int j=(int)(Math.random()*10);
code+=codees[j];
}
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", tel);
request.putQueryParameter("SignName", "IDSE");
request.putQueryParameter("TemplateCode", "SMS_175540528");
request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
CommonResponse response=null;
try {
response= client.getCommonResponse(request);
System.out.println(response.getData());
//獲取當前返回字符串轉換爲json對象
JSONObject json_object=JSONObject.parseObject(response.getData());
//根據鍵獲得值看是否爲“OK”,是則發送成功,返回驗證碼
String status=(String)json_object.get("Message");
if(status.equals("OK")){
return code;
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return null;
}
}