Java调用阿里云短信接口发送手机验证码
前五步可参考阿里云服务文档:https://help.aliyun.com/document_detail/59210.html?spm=a2c4g.11174283.4.1.2b152c42DoJ7Mt
一、入驻阿里云
1.阿里云注册入口:点击注册页面
2.实名认证:点击进行实名认证
二、开通短信服务
1.开通短信服务:点击开通短信服务
2.进入控制台:点击查看控制台页面
三、获取AccessKey
1创建AccessKey: 点击创建AccessKey
2.获取AccessKey ID和AccessKey Secret:点击查看AccessKey ID和AccessKey Secret
记得保存AccessKey ID和 AccessKey Secret
四、创建短信签名和模版
1.创建签名前查看短信规则和审核规则:短信业务规则,审核规则
2.创建短信签名:点击查看创建短信签名
3.创建短信模版:点击查看创建短信模版
五、访问权限设置
设置访问权限控制:点击访问权限控制
六.Java调用接口代码
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; /* pom.xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.3</version> </dependency> */ public class SendSms { private String accessKeyId = ""; //输入你的AccessKey ID private String accessSecret = ""; //输入你的AccessKey Secret public static void sendMessage(String phoneNumber, String code) { //手机号、验证码 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret); 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", "cn-hangzhou"); request.putQueryParameter("PhoneNumbers", phoneNumber); request.putQueryParameter("SignName", "签名名称"); //输入你的短信签名名称 request.putQueryParameter("TemplateCode", "SMS_000000000"); //输入你的短信模板ID request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}"); try { CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); return response.getHttpStatus() == 200 && response.getData().contains("\"Code\":\"OK\""); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } return false; } }