华为云中短信服务
创建 SendMsg :
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
/**
* maven 依赖配置
* <dependency>
* <groupId>org.apache.httpcomponents</groupId>
* <artifactId>fluent-hc</artifactId>
* <version>4.5.5</version>
* </dependency>
*/
public class SendMsg {
// 用于格式化鉴权头域,给“X-WSSE”参数赋值
private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
// 用于格式化鉴权头域,给“Authorization”参数赋值
private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";
/*
* public static void main(String[] args) throws Exception {
*
* System.out.println(sendAllMsg("", "+8613716888888",
* "",
* "[\"先生\",\"2018/09/19\",\"14:30\",\"100989\",\"13716888888\"]")); }
*/
public static String sendAllMsg(String sender, String receiver, String templateId, String templateParas)
throws ClientProtocolException, UnsupportedEncodingException, IOException {
// 开发准备:APP接入地址 + 接口访问URI
String url = "https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1";
// 开发准备:APP_Key
String appKey = "";
// 开发准备:APP_Secret
String appSecret = "";
// 开发准备:签名通道号
// String sender = "";
// 填写短信接收人号码,多个号码之间用英文逗号分隔
// String receiver = "+8613716888888,+8618606666666";
// 状态报告接收地址,为空或者不填表示不接收状态报告
String statusCallBack = "";
// 开发准备:模板ID
// String templateId = "";
// 模板变量请务必根据实际情况修改,查看更多模板变量规则
// 如模板内容为“您有${NUM_2}件快递请到${TXT_32}领取”时,templateParas可填写为[\"3\",\"人民公园正门\"]
// 双变量示例:String templateParas = "[\"3\",\"人民公园正门\"]";
// String templateParas =
// "[\"周先生\",\"2018/09/19\",\"14:30\",\"100819\",\"18606026926\"]";
// 请求Body
String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack);
System.out.println("body is " + body);
// 请求Headers中的X-WSSE参数值
String wsseHeader = buildWsseHeader(appKey, appSecret);
System.out.println("wsse header is " + wsseHeader);
// 如果JDK版本是1.8,可使用如下代码
CloseableHttpClient client;
HttpResponse response = null;
try {
client = HttpClients.custom()
.setSSLContext(
new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
response = client.execute(RequestBuilder.create("POST").setUri(url)
.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
.addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE).addHeader("X-WSSE", wsseHeader)
.setEntity(new StringEntity(body)).build());
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// EntityUtils.toString(response.getEntity()));
String responseEntity = EntityUtils.toString(response.getEntity());
// 判断是否发送成功,发送成功返回true
System.out.println(responseEntity);
String code = JSON.parseObject(responseEntity).getString("code");
String description = JSON.parseObject(responseEntity).getString("description");
/*
* System.out.println(code); System.out.println(description);
*/
if (code.equals("000000") && description.equals("Success")) {
return "success";
}
return "error";
}
static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
String statusCallbackUrl) {
List<NameValuePair> keyValues = new ArrayList<NameValuePair>();
keyValues.add(new BasicNameValuePair("from", sender));
keyValues.add(new BasicNameValuePair("to", receiver));
keyValues.add(new BasicNameValuePair("templateId", templateId));
keyValues.add(new BasicNameValuePair("templateParas", templateParas));
keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
// 如果JDK版本是1.6,可使用:URLEncodedUtils.format(keyValues,
// Charset.forName("UTF-8"));
return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8);
}
static String buildWsseHeader(String appKey, String appSecret) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String time = sdf.format(new Date());
String nonce = UUID.randomUUID().toString().replace("-", "");
byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
String hexDigest = Hex.encodeHexString(passwordDigest);
String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8")));
return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
}
}
调用函数发送短信:
// sender 签名通道号
// mobiles 电话号码
// teid 模板ID
// params 模板参数
String re = Send.sendAllMsg(sender, mobiles, teid, params);