本文为您介绍了Java调用SendMessageWithTemplate发送中国地区短信。
请求参数
名称 | 类型 | 是否必选 | 示例值 | 描述 |
---|---|---|---|---|
To | String | 是 | 45***0121 | 接收方的手机号码。说明:号码格式为国家码+号码。 |
From | String | 否 | XXCompany | 发送方标识;说明:发往中国时,该参数为短信签名。 |
TemplateCode | String | 是 | SMS_0000 | 短信模板ID。请在控制台中查看。 |
TemplateParam | String | 选填 | {“code”:”1234”,”product”:”ytx”} | 短信模板变量对应的实际值,JSON格式。
说明 如果JSON中需要带换行符,请参照标准的JSON协议处理。
|
SmsUpExtendCode | String | 选填 | 90999 | 上行短信扩展码,无特殊需要此字段的用户请忽略此字段。 |
返回数据
名称 | 类型 | 示例值 | 描述 |
---|---|---|---|
To | String | 45***0121 | 接收方的手机号码。说明:号码格式为国家码+号码。 |
MessageId | String | 100803***03003 | 短信发送ID,可根据该ID在接口QueryMessage中查询具体的发送状态。 |
ResponseCode | String | OK | 请求状态码,返回OK代表请求成功,其他错误码详见错误码列表。 |
ResponseDescription | String | 短信接收成功 | 状态码的描述。 |
Segments | String | 1 | 短信计费条数。 |
引入阿里云核心包
- 方法1:maven
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.4.6</version> </dependency>
- 方法2:core-sdk下载地址:Java API SDK。
调用示例
注意事项如下:
- 构造DefaultProfile时,第一个参数(regionId)必须为ap-southeast-1,请勿修改。
- domain必须为dysmsapi.ap-southeast-1.aliyuncs.com,请勿修改。
- version必须为2018-05-01,请勿修改。
package com.alicom.dysms.api;
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.4.6</version>
</dependency>
*/
public class CommonRpc {
public static void main(String[] args) {
//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
DefaultProfile profile = DefaultProfile.getProfile("ap-southeast-1", "<accessKeyId>", "<accessSecret>");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
//域名,请勿修改
request.setDomain("dysmsapi.ap-southeast-1.aliyuncs.com");
//API版本号,请勿修改
request.setVersion("2018-05-01");
//API名称
request.setAction("SendMessageWithTemplate");
//接收号码,格式为:国际码+号码,必填
request.putQueryParameter("To", "8615200000000");
request.putQueryParameter("From", "云通信签名");
request.putQueryParameter("TemplateCode", "SMS_225001");
request.putQueryParameter("TemplateParam", "{\"code\":\"1234\"}");
request.putQueryParameter("SmsUpExtendCode", "12345");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}