作为项目使用,学习调用阿里云的短信接口,记录下学习笔记。
首先需要购买阿里云的短信服务,下载对应的SDK(这里是Java的),创建短信签名,创建短信模板
需要获取阿里云短信API的AccessKey
SDK下载:http://aliyundm.oss-cn-hangzhou.aliyuncs.com/example/aliyun-java-sdk-smsV1.zip
通过maven添加依赖:
<!-- 阿里云短信服务 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sms</artifactId>
<version>3.0.0-rc1</version>
</dependency>
实际开发应用:(在测试类中测试使用)
import org.junit.Test;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest;
import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse;
public class ALiYunTest {
//阿里云短信服务regionID
private static final String REGIONID = "cn-hangzhou";
//阿里云短信服务key
private static final String ACCESSKEYID = "你的accesskeyID";
//阿里云短信服务secret
private static final String SECRET = "你的secret";
@Test
public void test() {
IClientProfile profile = DefaultProfile.getProfile(REGIONID, ACCESSKEYID, SECRET);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com");
} catch (ClientException e1) {
e1.printStackTrace();
}
IAcsClient client = new DefaultAcsClient(profile);
SingleSendSmsRequest request = new SingleSendSmsRequest();
try{
request.setSignName("你的注册名");
request.setTemplateCode("你的短信模板编号");
request.setParamString("你的短信模板(以JSon格式在阿里平台编译好)");//例:{\"code\":\"" + "569725" + "\",\"product\":" + "\"阿里小店\"}
request.setRecNum("用户手机号");
@SuppressWarnings("unused")
SingleSendSmsResponse httpResponse = client.getAcsResponse(request);
}catch(ServerException e) {
e.printStackTrace();
}catch(ClientException e) {
e.printStackTrace();
}
}
}
测试收发验证码短信。