更新时间:2024-04-08 GMT+08:00
分享

Java

  • 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。
  • 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。
  • 本文档信息仅供参考,不构成任何要约或承诺。

发送短信

package sms; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.URL; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
 
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; 
 
 
// If the JDK version is earlier than 1.8, use the third-party library to provide the Base64 class. 
public class SendSms { 
    /** 
     * 设置不验证主机 
     */ 
 
 
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 
 
 
        @Override 
        public boolean verify(String hostname, SSLSession session) { 
 
 
            return true; 
 
 
        } 
 
 
    }; 
 
 
    public static void main(String[] args) throws Exception { 
        //APP接入地址+接口访问URI, IP:Port表示IoT云通信的IP和端口号,IP和端口信息在申请开通接入完成后会自动分配,可在控制台-国内短信-开通接入页面进行查看。
        String url = "https://ip:port/common/sms/sendTemplateMessage"; 
        String[] msisdn = {"8612345678911", "8612345678912"}; //手机号,支持传入多个,需要list格式,若只需传入1个,格式为:{"8612345678911"}
        String smsTemplateId = "SMS_2003240016"; //模板编号
        //当发送短信使用的是无变量模板时,不需要templateParas对象,请删除该对象。
        Map<String, String> templateParas = new HashMap<String, String>(); 
        //当发送短信使用的是带变量的模板时,需要配置本行代码。VarName表示模板中变量的参数名称,VarValue表示该变量实际要配置的参数值,请按照实际情况配置VarName和VarValue。若需要配置多个变量,请参考本行代码格式进行添加。
        templateParas.put("VarName", "VarValue"); 
        String accout = "account"; //实际账号 
        String passward = "passward"; //实际密码 
 
 
        // If the request body does not contain the signature name, set signature to null. 
        Map<String, Object> body = buildRequestBody(msisdn, smsTemplateId, templateParas, accout, passward); 
        if (null == body || body.isEmpty()) { 
            System.out.println("body is null."); 
            return; 
        } 
 
 
        HttpsURLConnection connection = null; 
        InputStream is = null; 
        BufferedReader br = null; 
        trustAllHttpsCertificates(); 
        try { 
 
 
            URL realUrl = new URL(url); 
            connection = (HttpsURLConnection) realUrl.openConnection(); 
            connection.setHostnameVerifier(DO_NOT_VERIFY); 
            connection.setDoInput(true); // 设置可输入 
            connection.setDoOutput(true); // 设置该连接是可以输出的 
            connection.setRequestMethod("POST"); // 设置请求方式 
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
            // connection.connect(); 
            ObjectMapper objectMapper = new ObjectMapper(); 
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); 
            pw.write(objectMapper.writeValueAsString(body)); 
            pw.flush(); 
            pw.close(); 
 
 
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); 
            int status = connection.getResponseCode(); 
            if (200 == status) { // 200 
                is = connection.getInputStream(); 
            } else { // 400/401 
                is = connection.getErrorStream(); 
            } 
            br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
            String line = null; 
            StringBuilder result = new StringBuilder(); 
            while ((line = br.readLine()) != null) { // 读取数据 
                result.append(line + "\n"); 
            } 
            connection.disconnect(); 
            System.out.println(result.toString()); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
 
 
                if (null != is) { 
                    is.close(); 
                } 
                if (null != br) { 
                    br.close(); 
                } 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
 
 
    // msisdn, smsTemplateId, paramValues, countryID 
    public static Map<String, Object> buildRequestBody(String[] msisdn, String smsTemplateId, 
        Map<String, String> paramValues, String accout, String passward) { 
        if (null == msisdn || null == smsTemplateId || null == accout || null == passward) { 
            System.out.println( 
                "buildRequestBody(): mobiles, templateId or templateParas or account or password is null."); 
            return null; 
        } 

        List<String> mobiles = new ArrayList<String>();
        // 多个手机号参数
        for(String mobile: msisdn) {
            mobiles.add(mobile);
        }
 
        Map<String, Object> map = new HashMap<String, Object>(); 
        List<MtSmsMessage> requestLists = new ArrayList<MtSmsMessage>(); 
        MtSmsMessage mtSmsMessage = new MtSmsMessage();  
        mtSmsMessage.setMobiles(mobiles); 
        mtSmsMessage.setTemplateId(smsTemplateId); 
        //当发送短信使用的是无变量模板时,不需要给TemplateParas对象赋值。
        mtSmsMessage.setTemplateParas(paramValues); 
        mtSmsMessage.setSignature("【华为云】"); //短信签名
        requestLists.add(mtSmsMessage); 
        map.put("account", accout); 
        map.put("password", passward); 
        map.put("requestLists", requestLists); 
        return map; 
    } 
 
 
    public static class MtSmsMessage { 
        List<String> mobiles; 
 
 
        String templateId; 
 
 
        Map<String, String> templateParas; 
 
 
        String signature; 
 
 
        String messageId; 
 
 
        String extCode; 
 
 
        List<NamedParameter> extendInfos; 
 
 
        /** 
         * 返回 mobiles 
         * 
         * @return mobiles值 
         */ 
        public List<String> getMobiles() { 
            return mobiles; 
        } 
 
 
        /** 
         * 对mobiles进行赋值 
         * 
         * @param mobiles mobiles值 
         */ 
        public void setMobiles(List<String> mobiles) { 
            this.mobiles = mobiles; 
        } 
 
 
        /** 
         * 返回 templateId 
         * 
         * @return templateId值 
         */ 
        public String getTemplateId() { 
            return templateId; 
        } 
 
 
        /** 
         * 对templateId进行赋值 
         * 
         * @param templateId templateId值 
         */ 
        public void setTemplateId(String templateId) { 
            this.templateId = templateId; 
        } 
 
 
        /** 
         * 返回 templateParas 
         * 
         * @return templateParas值 
         */ 
        public Map<String, String> getTemplateParas() { 
            return templateParas; 
        } 
 
 
        /** 
         * 对templateParas进行赋值 
         * 
         * @param templateParas templateParas值 
         */ 
        public void setTemplateParas(Map<String, String> templateParas) { 
            this.templateParas = templateParas; 
        } 
 
 
        /** 
         * 返回 signature 
         * 
         * @return signature值 
         */ 
        public String getSignature() { 
            return signature; 
        } 
 
 
        /** 
         * 对signature进行赋值 
         * 
         * @param signature signature值 
         */ 
        public void setSignature(String signature) { 
            this.signature = signature; 
        } 
 
 
        /** 
         * 返回 messageId 
         * 
         * @return messageId值 
         */ 
        public String getMessageId() { 
            return messageId; 
        } 
 
 
        /** 
         * 对messageId进行赋值 
         * 
         * @param messageId messageId值 
         */ 
        public void setMessageId(String messageId) { 
            this.messageId = messageId; 
        } 
 
 
        /** 
         * 返回 extCode 
         * 
         * @return extCode值 
         */ 
        public String getExtCode() { 
            return extCode; 
        } 
 
 
        /** 
         * 对extCode进行赋值 
         * 
         * @param extCode extCode值 
         */ 
        public void setExtCode(String extCode) { 
            this.extCode = extCode; 
        } 
 
 
        /** 
         * 返回 extendInfos 
         * 
         * @return extendInfos值 
         */ 
        public List<NamedParameter> getExtendInfos() { 
            return extendInfos; 
        } 
 
 
        /** 
         * 对extendInfos进行赋值 
         * 
         * @param extendInfos extendInfos值 
         */ 
        public void setExtendInfos(List<NamedParameter> extendInfos) { 
            this.extendInfos = extendInfos; 
        } 
 
 
    } 
 
 
    public class NamedParameter { 
        String key; 
 
 
        String value; 
 
 
        /** 
         * 返回 key 
         * 
         * @return key值 
         */ 
        public String getKey() { 
            return key; 
        } 
 
 
        /** 
         * 对key进行赋值 
         * 
         * @param key key值 
         */ 
        public void setKey(String key) { 
            this.key = key; 
        } 
 
 
        /** 
         * 返回 value 
         * 
         * @return value值 
         */ 
        public String getValue() { 
            return value; 
        } 
 
 
        /** 
         * 对value进行赋值 
         * 
         * @param value value值 
         */ 
        public void setValue(String value) { 
            this.value = value; 
        } 
 
 
    } 
 
 
    static void trustAllHttpsCertificates() throws Exception { 
        // 如果您不需要校验证书时,请使用如下代码
        TrustManager[] trustAllCerts = new TrustManager[] { 
            new X509TrustManager() { 
                @Override 
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
                    return; 
                } 
 
 
                @Override 
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
                    return; 
                } 
 
 
                @Override 
                public X509Certificate[] getAcceptedIssuers() { 
                    return null; 
                } 
            } 
        }; 
        
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        /**
         * 如果您不需要校验证书时,请使用如下代码
         * TrustManager[] trustAllCerts = new TrustManager[] {
         *       new X509TrustManager() {
         *           @Override
         *           public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
         *               return;
         *           }
         *
         *           @Override
         *           public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
         *               return;
         *           }
         *
         *           @Override
         *           public X509Certificate[] getAcceptedIssuers() {
         *               return null;
         *           }
         *       }
         * };
         * sslContext.init(null, trustAllCerts, SecureRandom.getInstanceStrong());
         */

        // 如果您需要校验证书时,请使用如下代码
        // 构建TrustManagerFactory
        File trustFile = new File("你的trustStore证书库文件路径");
        fsTruststoreFile = new FileInputStream(trustFile);
        KeyStore trustStore = KeyStore.getInstance("JKS");
        String trustStorePwd = "你的trustStore证书库密码明文";
        trustStore.load(fsTruststoreFile, trustStorePwd.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        // 构建KeyManagerFactory
        File keyFile = new File("你的keyStore证书库文件路径");
        fsKeystoreFile = new FileInputStream(keyFile);
        KeyStore keyStore = KeyStore.getInstance("JKS");
        String keyStorePwd = "你的keyStore证书库密码明文";
        keyStore.load(fsKeystoreFile, keyStorePwd.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePwd.toCharArray());
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), SecureRandom.getInstanceStrong());       
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
    } 
}

上行短信接收

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 上行短信通知 短信平台通过客户添加应用时配置的上行短信接收地址推送上行短信通知给客户
 */
public class SmsUpData {
    public static void main(String[] args) throws Exception {

        // 上行短信通知样例(urlencode)
         String upData = "mobile=12345678911&content=***&sendTime=20220127020758&extCode=";
		
         onSmsUpData(upData);
    }

    /**
     * 解析上行短信通知数据
     * 
     * @param data 短信平台推送的上行短信通知数据
     */
    static void onSmsUpData(String data) {

        if (null == data || data.isEmpty()) {
            System.out.println("onSmsUpData(): data is null.");
            return;
        }
        Map<String, String> keyValues = new HashMap<String, String>();
        try {
            // 解析上行短信通知数据
            String[] params = URLDecoder.decode(data, "UTF-8").split("&");
            String[] temp;
            for (int i = 0; i < params.length; i++) {
                temp = params[i].split("=");
                if (temp.length == 2 && null != temp[1] && temp[1] != "") {
                    keyValues.put(temp[0], temp[1]);
                }
            }

            /**
             * Example: 此处以解析content为例,请按需解析所需参数并自行实现相关处理
             * 
             * 'mobile': 上行短信手机号
             * 'content': 短信内容
             * 'sendTime': 上行短信时间
             * 'extCode': 扩展码
             */
            String content = keyValues.get("content"); // 上行短信发送的内容
            System.out.println("Sms up data. Content: " + content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

状态报告接收

import com.libaitest.libaimock.demo.StatusCallbackRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信状态报告 短信平台收到短信网关的状态报告,或超过72小时自主构建状态报告消息通过回调地址推送给客户
 */
@RestController
public class StatusReportImpl {

    @PostMapping(path = "/common/sms/notifyReportMessage")
    public Result notifyReportMessage(@RequestBody StatusCallbackRequest statusCallbackRequest) {
        Result result = new Result("0", "success");
		// 通过status判断短信是否发送成功
        if ("DELIVRD".equalsIgnoreCase(statusCallbackRequest.getStatus())) {
            System.out.println("Send sms success. messageId: " + statusCallbackRequest.getMessageId());
        } else {
            System.out.println("Send sms failed. messageId: " + statusCallbackRequest.getMessageId());
            System.out.println("Failed status: " + statusCallbackRequest.getStatus());
        }
        return result;
    }
}

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.List;

/**
 * 短信状态报告请求实体类
 */
@Getter
@Setter
@ToString
public class StatusCallbackRequest {

	// 用于与下发消息时的requestId进行关联
    private String requestId;

	// 下发手机号码
    private String mobile;

    // 短信消息id,短信唯一标识
    private String messageId;

	// 状态码
    private String status;

	// 长短信拆分条数
    private Integer smsCount;

	// 终端用户收到短信的时间
    private String receiveTime;

	// 扩展字段
    private List<NamedParameter> extendInfos;

}

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * 短信状态报告请求实体类 扩展字段对应消息体
 */
@Getter
@Setter
@ToString
public class NamedParameter {

    protected String key;

    protected String value;

}

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 短信状态报告响应消息实体类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
    private String resultCode;
    private String resultDesc;
}

相关文档