华为云短信发送验证码并判断是否成功
代码复制于华为云官方文档,基本拿来即用
需要准备
1、url,你的APP接入地址(在控制台"应用管理"页面获取) 接口访问URI
2、APP_Key
3、APP_Secret
4、国内短信签名通道号或国际/港澳台短信通道号
5、模板ID
6、签名名称
这些在华为云可获取,APP_Secret需要验证账号手机号来获取
其中
Authorization 的值默认为
WSSE realm="SDP",profile="UsernameToken",type="Appkey"
WSSE_HEADER_FORMAT 的值默认为
UsernameToken Username="%s",PasswordDigest="%s",Nonce="%s",Created="%s"
-
-
import com.alibaba.fastjson.JSONObject;
-
import com.systop.common.constant.Constants;
-
-
import java.io.BufferedReader;
-
import java.io.InputStream;
-
import java.io.InputStreamReader;
-
import java.io.OutputStreamWriter;
-
import java.io.UnsupportedEncodingException;
-
import java.io.Writer;
-
import java.net.URL;
-
import java.net.URLEncoder;
-
import java.security.MessageDigest;
-
import java.security.NoSuchAlgorithmException;
-
import java.security.cert.CertificateException;
-
import java.security.cert.X509Certificate;
-
import java.text.SimpleDateFormat;
-
//如果JDK版本是1.8,可使用原生Base64类
-
import java.util.Base64;
-
import java.util.Date;
-
import java.util.HashMap;
-
import java.util.Map;
-
import java.util.UUID;
-
import java.util.stream.Collectors;
-
-
import javax.net.ssl.HostnameVerifier;
-
import javax.net.ssl.HttpsURLConnection;
-
import javax.net.ssl.SSLContext;
-
import javax.net.ssl.SSLSession;
-
import javax.net.ssl.TrustManager;
-
import javax.net.ssl.X509TrustManager;
-
/**
-
* @auther 陈伟龙
-
* @date 2022/10/10 - 9:26
-
*/
-
public class HuaweiSmsCode {
-
-
public static void main(String[] args) throws Exception {
-
-
//必填,请参考"开发准备"获取如下数据,替换为实际值
-
String url = Constants.HW_URL; //APP接入地址(在控制台"应用管理"页面获取) 接口访问URI
-
String appKey = Constants.HW_APPKEY; //APP_Key
-
String appSecret = Constants.HW_APPSECRET; //APP_Secret
-
String sender = Constants.HW_SENDER; //国内短信签名通道号或国际/港澳台短信通道号
-
String templateId = Constants.HW_TEMPLATEID; //模板ID
-
-
//条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
-
//国际/港澳台短信不用关注该参数
-
String signature = Constants.HW_TEMPLATESIGNATURE; //签名名称
-
-
//必填,全局号码格式(包含国家码),示例: 8615123456789,多个号码之间用英文逗号分隔
-
String receiver = "155xxxx0910"; //短信接收人号码
-
-
//选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
-
String statusCallBack = "";
-
-
/**
-
* 选填,使用无变量模板时请赋空值 String templateParas = "";
-
* 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
-
* 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
-
* 模板中的每个变量都必须赋值,且取值不能为空
-
* 查看更多模板和变量规范:产品介绍>模板和变量规范
-
*/
-
String templateParas = "[\"369751\"]"; //模板变量,此处以单变量验证码短信为例,请客户自行生成6位验证码,并定义为字符串类型,以杜绝首位0丢失的问题(例如:002569变成了2569)。
-
-
//请求Body,不携带签名名称时,signature请填null
-
String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);
-
if (null == body || body.isEmpty()) {
-
System.out.println("body is null.");
-
return;
-
}
-
-
//请求Headers中的X-WSSE参数值
-
String wsseHeader = buildWsseHeader(appKey, appSecret);
-
if (null == wsseHeader || wsseHeader.isEmpty()) {
-
System.out.println("wsse header is null.");
-
return;
-
}
-
-
Writer out = null;
-
BufferedReader in = null;
-
StringBuffer result = new StringBuffer();
-
HttpsURLConnection connection = null;
-
InputStream is = null;
-
-
-
HostnameVerifier hv = new HostnameVerifier() {
-
-
-
public boolean verify(String hostname, SSLSession session) {
-
return true;
-
}
-
};
-
trustAllHttpsCertificates();
-
-
try {
-
URL realUrl = new URL(url);
-
connection = (HttpsURLConnection) realUrl.openConnection();
-
-
connection.setHostnameVerifier(hv);
-
connection.setDoOutput(true);
-
connection.setDoInput(true);
-
connection.setUseCaches(true);
-
//请求方法
-
connection.setRequestMethod("POST");
-
//请求Headers参数
-
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
-
connection.setRequestProperty("Authorization", Constants.HW_AUTH_HEADER_VALUE);
-
connection.setRequestProperty("X-WSSE", wsseHeader);
-
-
connection.connect();
-
out = new OutputStreamWriter(connection.getOutputStream());
-
out.write(body); //发送请求Body参数
-
out.flush();
-
out.close();
-
-
int status = connection.getResponseCode();
-
if (200 == status) { //200
-
is = connection.getInputStream();
-
} else { //400/401
-
is = connection.getErrorStream();
-
}
-
in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
-
String line = "";
-
while ((line = in.readLine()) != null) {
-
result.append(line);
-
}
-
System.out.println(result.toString()); //打印响应消息实体
-
JSONObject rsJson = JSONObject.parseObject(String.valueOf(result));
-
System.out.println(rsJson.getString("code"));
-
System.out.println(rsJson.getJSONArray("result").getJSONObject(0).getString("status"));
-
-
// JSONObject jsonresult = JSONObject.parseObject(rsJson.getString("result"));
-
// System.out.println(jsonresult);
-
} catch (Exception e) {
-
e.printStackTrace();
-
} finally {
-
try {
-
if (null != out) {
-
out.close();
-
}
-
if (null != is) {
-
is.close();
-
}
-
if (null != in) {
-
in.close();
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
-
/**
-
* 构造请求Body体
-
* @param sender
-
* @param receiver
-
* @param templateId
-
* @param templateParas
-
* @param statusCallBack
-
* @param signature | 签名名称,使用国内短信通用模板时填写
-
* @return
-
*/
-
static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
-
String statusCallBack, String signature) {
-
if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
-
|| templateId.isEmpty()) {
-
System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
-
return null;
-
}
-
Map<String, String> map = new HashMap<String, String>();
-
-
map.put("from", sender);
-
map.put("to", receiver);
-
map.put("templateId", templateId);
-
if (null != templateParas && !templateParas.isEmpty()) {
-
map.put("templateParas", templateParas);
-
}
-
if (null != statusCallBack && !statusCallBack.isEmpty()) {
-
map.put("statusCallback", statusCallBack);
-
}
-
if (null != signature && !signature.isEmpty()) {
-
map.put("signature", signature);
-
}
-
-
StringBuilder sb = new StringBuilder();
-
String temp = "";
-
-
for (String s : map.keySet()) {
-
try {
-
temp = URLEncoder.encode(map.get(s), "UTF-8");
-
} catch (UnsupportedEncodingException e) {
-
e.printStackTrace();
-
}
-
sb.append(s).append("=").append(temp).append("&");
-
}
-
-
return sb.deleteCharAt(sb.length()-1).toString();
-
}
-
-
/**
-
* 构造X-WSSE参数值
-
* @param appKey
-
* @param appSecret
-
* @return
-
*/
-
static String buildWsseHeader(String appKey, String appSecret) {
-
if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
-
System.out.println("buildWsseHeader(): appKey or appSecret is null.");
-
return null;
-
}
-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
-
String time = sdf.format(new Date()); //Created
-
String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce
-
-
MessageDigest md;
-
byte[] passwordDigest = null;
-
-
try {
-
md = MessageDigest.getInstance("SHA-256");
-
md.update((nonce time appSecret).getBytes());
-
passwordDigest = md.digest();
-
} catch (NoSuchAlgorithmException e) {
-
e.printStackTrace();
-
}
-
-
//如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
-
String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest); //PasswordDigest
-
//如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
-
//String passwordDigestBase64Str = Base64.encodeBase64String(passwordDigest); //PasswordDigest
-
//若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
-
//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");
-
return String.format(Constants.HW_WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
-
}
-
-
/*** @throws Exception
-
*/
-
static void trustAllHttpsCertificates() throws Exception {
-
TrustManager[] trustAllCerts = new TrustManager[] {
-
new X509TrustManager() {
-
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-
return;
-
}
-
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-
return;
-
}
-
public X509Certificate[] getAcceptedIssuers() {
-
return null;
-
}
-
}
-
};
-
SSLContext sc = SSLContext.getInstance("SSL");
-
sc.init(null, trustAllCerts, null);
-
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
-
}
-
}
1、注意url 一定是
https://smsapi.cn-south-1.myhuaweicloud.com:443/sms/batchSendSms/v1
2、返回值的json样式为
{"result":[{"originTo":"155xxxx0910","createTime":"2022-10-10T03:05:14Z","from":"8822100825173","smsMsgId":"cf8290e2-30ee-4c34-8874-83c8de2e99b9_16142890744","status":"000000"}],"code":"000000","description":"Success"}
3、获取code和status的值判断是否返回成功,000000应该就是发送成功了
rsJson.getString("code")
rsJson.getJSONArray("result").getJSONObject(0).getString("status")
Constants字典类图片展示(部分数据不便展示)
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhibfcfg
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
微信运动停用后别人还能看到步数吗
PHP中文网 07-22 -
excel打印预览压线压字怎么办
PHP中文网 06-22