关于华为云短信接口对接问题
生活随笔
收集整理的這篇文章主要介紹了
关于华为云短信接口对接问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
華為云---消息&短信
- 對接API
- 問題
對接API
華為云基礎示例
https://support.huaweicloud.com/devg-msgsms/sms_04_0002.html
自定義項目工具類
package com.china.xxx;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.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 org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service;import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.*;public class HuaweiMessageApi {//無需修改,用于格式化鑒權頭域,給"X-WSSE"參數賦值private final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";//無需修改,用于格式化鑒權頭域,給"Authorization"參數賦值private final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";@Value("${huaweiSms.url}")private String url; //APP接入地址+接口訪問URI@Value("${huaweiSms.appKey}")private String appKey; //APP_Key@Value("${huaweiSms.appSecret}")private String appSecret; //APP_Secret@Value("${huaweiSms.sender}")private String sender; //國內短信簽名通道號或國際/港澳臺短信通道號@Value("${huaweiSms.signature}")private String signature; //簽名名稱public void sendMessage(String templateId, String receiver, String templateParas){//receiver = "18500851993"; //短信接收人號碼String statusCallBack = "";/*** 選填,使用無變量模板時請賦空值 String templateParas = "";* 單變量模板示例:模板內容為"您的驗證碼是${1}"時,templateParas可填寫為"[\"369751\"]"* 雙變量模板示例:模板內容為"您有${1}件快遞請到${2}領取"時,templateParas可填寫為"[\"3\",\"人民公園正門\"]"* 模板中的每個變量都必須賦值,且取值不能為空* 查看更多模板和變量規范:產品介紹>模板和變量規范*///String templateParas = "[\"" + content + "\"]";//請求Body,不攜帶簽名名稱時,signature請填nullString 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;}try {//如果JDK版本是1.8,可使用如下代碼//為防止因HTTPS證書認證失敗造成API調用失敗,需要先忽略證書信任問題CloseableHttpClient client = HttpClients.custom().setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,(x509CertChain, authType) -> true).build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();HttpResponse response = client.execute(RequestBuilder.create("POST")//請求方法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());System.out.println(response.toString()); //打印響應頭域信息System.out.println(EntityUtils.toString(response.getEntity())); //打印響應消息實體} catch (Exception e) {e.printStackTrace();}}/*** 構造請求Body體** @param sender* @param receiver* @param templateId* @param templateParas* @param statusCallbackUrl* @param signature | 簽名名稱,使用國內短信通用模板時填寫* @return*/static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,String statusCallbackUrl, 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;}List<NameValuePair> keyValues = new ArrayList<NameValuePair>();keyValues.add(new BasicNameValuePair("from", sender));keyValues.add(new BasicNameValuePair("to", receiver));keyValues.add(new BasicNameValuePair("templateId", templateId));if (null != templateParas && !templateParas.isEmpty()) {keyValues.add(new BasicNameValuePair("templateParas", templateParas));}if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));}if (null != signature && !signature.isEmpty()) {keyValues.add(new BasicNameValuePair("signature", signature));}return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));}/*** 構造X-WSSE參數值** @param appKey* @param appSecret* @return*/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()); //CreatedString nonce = UUID.randomUUID().toString().replace("-", ""); //Noncebyte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);String hexDigest = Hex.encodeHexString(passwordDigest);//如果JDK版本是1.8,請加載原生Base64類,并使用如下代碼String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest//若passwordDigestBase64Str中包含換行符,請執行如下代碼進行修正//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);} }問題
小編發現問題,就是所有短信必須帶有標簽,如果沒有標簽是不允許發送
總結
以上是生活随笔為你收集整理的关于华为云短信接口对接问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 武汉电博会看点 daydao电商云ERP
- 下一篇: 经验分享——关于大学生科研那些事