Help Center/
Message & SMS/
Developer Guide/
Code Examples/
AK/SK Authentication (Recommended)/
Java
Updated on 2024-07-03 GMT+08:00
Java
Example |
|
---|---|
Environment |
JDK 1.8 or later |
Download required SDKs and demos for Java. Copy the following code sample to a new Java file and run it.
- Sending SMSs shows an example of sending group SMSs with a single template. Sending SMSs in batches shows an example of sending group SMSs with multiple templates.
- The examples described in this document may involve the use of personal data. You are advised to comply with relevant laws and regulations and take measures to ensure that personal data is fully protected.
- The examples described in this document are for demonstration purposes only. Commercial use of the examples is prohibited.
- Information in this document is for your reference only. It does not constitute any offer or commitment.
Example of Sending SMSs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
import com.cloud.apigateway.sdk.utils.Client; import com.cloud.apigateway.sdk.utils.Request; import com.huawei.apig.sdk.util.Constant; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; public class SendSms { private static final Logger LOGGER = LoggerFactory.getLogger(SendSms.class); public static final String UTF_8 = "UTF-8"; private static CloseableHttpClient client = null; public static void main(String[] args) throws Exception { // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures. client = createIgnoreSSLHttpClient(); sendSms(); } private static void sendSms() throws IOException { // Mandatory. The values here are example values only. Obtain the values based on Development Preparation. String url = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendSms/v1"; // Application access address and API access URI // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables. String appKey = "c8RWg3gg************3Y7x1Ile"; //Application Key String appSecret = "q4Ii87Bh************80SfD7Al"; //Application Secret String sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS String templateId = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template. // This parameter is not required for international SMS. String signature = "Huawei Cloud SMS test"; // Signature // Mandatory. Global number format (including the country code), for example, +86151****6789. Use commas (,) to separate multiple numbers. String receiver = "+86151****6789,+86152****7890"; // Recipient numbers // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports. String statusCallBack = ""; /** * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, String templateParas = ""; * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to "[\"111111\"]". * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to "[\"3\",\"main gate of People's Park\"]". * To view more information, choose Service Overview > Template and Variable Specifications. */ String templateParas = "[\"111111\"]"; // Template variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). // Request body. If the signature name is not required, set signature to null. String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature); if (null == body || body.isEmpty()) { LOGGER.warn("body is null."); return; } Request request = new Request(); request.setKey(appKey); request.setSecret(appSecret); request.setMethod("POST"); request.setUrl(url); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.setBody(body); LOGGER.info("Print the body: {}", body); try { HttpRequestBase signedRequest = Client.sign(request, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256); LOGGER.info("Print the authorization: {}", Arrays.toString(signedRequest.getHeaders("Authorization"))); Header[] requestAllHeaders = signedRequest.getAllHeaders(); for (Header h : requestAllHeaders) { LOGGER.info("req Header with name: {} and value: {}", h.getName(), h.getValue()); } HttpResponse response = client.execute(signedRequest); LOGGER.info("Print the status line of the response: {}", response.getStatusLine().toString()); Header[] resHeaders = response.getAllHeaders(); for (Header h : resHeaders) { LOGGER.info("Processing Header with name: {} and value: {}", h.getName(), h.getValue()); } HttpEntity resEntity = response.getEntity(); if (resEntity != null) { LOGGER.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"), EntityUtils.toString(resEntity, "UTF-8")); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } public static CloseableHttpClient createIgnoreSSLHttpClient() throws Exception { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build(); return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build(); } static String buildRequestBody(String sender, String receiver, String templateId, String templateParas, String statusCallBack, String signature) throws UnsupportedEncodingException { 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; } StringBuilder body = new StringBuilder(); appendToBody(body, "from=", sender); appendToBody(body, "&to=", receiver); appendToBody(body, "&templateId=", templateId); appendToBody(body, "&templateParas=", templateParas); appendToBody(body, "&statusCallback=", statusCallBack); appendToBody(body, "&signature=", signature); return body.toString(); } private static void appendToBody(StringBuilder body, String key, String val) throws UnsupportedEncodingException { if (null != val && !val.isEmpty()) { LOGGER.info("Print appendToBody: {}:{}", key, val); body.append(key).append(URLEncoder.encode(val, UTF_8)); } } } |
Example of Sending SMSs in Batches
Configure the following dependencies in Maven.
1 2 3 4 5 |
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180130</version> </dependency> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
import com.huawei.apig.sdk.util.Constant; import com.cloud.apigateway.sdk.utils.Client; import com.cloud.apigateway.sdk.utils.Request; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class SendDiffSms { private static final Logger LOGGER = LoggerFactory.getLogger(SendDiffSms.class); private static CloseableHttpClient client = null; public static void main(String[] args) throws Exception { // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures. client = createIgnoreSSLHttpClient(); sendSms(); } private static void sendSms() throws IOException { // Mandatory. The values here are example values only. Obtain the values based on Development Preparation. String url = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendDiffSms/v1"; // Application access address (obtain it from the Application Management page on the console) and API access URI. // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables. String appKey = "c8RWg3gg************3Y7x1Ile"; //APP_Key String appSecret = "q4Ii87Bh************80SfD7Al"; //APP_Secret String sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS String templateId1 = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID 1 String templateId2 = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID 2 // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template. // This parameter is not required for international SMS. String signature1 = "Huawei Cloud SMS test"; // Signature 1 String signature2 = "Huawei Cloud SMS test"; // Signature 2 // Mandatory. Global number format (including the country code), for example, +86151****6789. Use commas (,) to separate multiple numbers. String[] receiver1 = {"+86151****6789", "+86152****7890"}; // Recipient number of template 1 String[] receiver2 = {"+86151****6789", "+86152****7890"}; // Recipient number of template 2 // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports. String statusCallBack = ""; /** * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, String templateParas = {}; * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to {"111111"}. * Example of a dual-variable template: If the template content is "You have ${NUM_2} parcels delivered to ${TXT_20}", templateParas can be set to {"3","main gate of People's Park"}. * ${DATE}${TIME} cannot be empty. You can use spaces or dots (.) to replace the empty value of ${TXT_20} and use 0 to replace the empty value of ${NUM_6}. * To view more information, choose Service Overview > Template and Variable Specifications. */ String[] templateParas1 = { "123456" }; // Template 1 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). String[] templateParas2 = { "234567" }; // Template 2 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). // smsContent. If the signature name is not required, set signature to null. List<Map<String, Object>> smsContent = new ArrayList<Map<String, Object>>(); Map<String, Object> item1 = initDiffSms(receiver1, templateId1, templateParas1, signature1); Map<String, Object> item2 = initDiffSms(receiver2, templateId2, templateParas2, signature2); if (null != item1 && !item1.isEmpty()) { smsContent.add(item1); } if (null != item2 && !item2.isEmpty()) { smsContent.add(item2); } // Request body String body = buildRequestBody(sender, smsContent, statusCallBack); if (null == body || body.isEmpty()) { System.out.println("body is null."); return; } Request request = new Request(); request.setKey(appKey); request.setSecret(appSecret); request.setMethod("POST"); request.setUrl(url); request.addHeader("Content-Type", "application/json"); request.setBody(body); LOGGER.info("Print the body: {}", body); try { // Sign the request. HttpRequestBase signedRequest = Client.sign(request, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256); // Print request header parameters: Authorization LOGGER.info("Print the allHeaders: {}", Arrays.toString(signedRequest.getAllHeaders())); HttpResponse response = client.execute(signedRequest); // Print the status line of the response. LOGGER.info("Print the status line of the response: {}", response.getStatusLine().toString()); // Print the header fields of the response. Header[] resHeaders = response.getAllHeaders(); for (Header h : resHeaders) { LOGGER.info("Processing Header with name: {} and value: {}", h.getName(), h.getValue()); } // Print the body of the response. HttpEntity resEntity = response.getEntity(); if (resEntity != null) { LOGGER.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"), EntityUtils.toString(resEntity, "UTF-8")); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } public static CloseableHttpClient createIgnoreSSLHttpClient() throws Exception { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build(); return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build(); } static String buildRequestBody(String sender, List<Map<String, Object>> smsContent, String statusCallBack) { if (null == sender || null == smsContent || sender.isEmpty() || smsContent.isEmpty()) { System.out.println("buildRequestBody(): sender or smsContent is null."); return null; } JSONArray jsonArr = new JSONArray(); for (Map<String, Object> it : smsContent) { jsonArr.put(it); } Map<String, Object> data = new HashMap<String, Object>(); data.put("from", sender); data.put("smsContent", jsonArr); if (null != statusCallBack && !statusCallBack.isEmpty()) { data.put("statusCallback", statusCallBack); } return new JSONObject(data).toString(); } /** * Construct the value of smsContent. */ static Map<String, Object> initDiffSms(String[] receiver, String templateId, String[] templateParas, String signature) { if (null == receiver || null == templateId || receiver.length == 0 || templateId.isEmpty()) { System.out.println("initDiffSms(): receiver or templateId is null."); return null; } Map<String, Object> map = new HashMap<String, Object>(); map.put("to", receiver); map.put("templateId", templateId); if (null != templateParas && templateParas.length > 0) { map.put("templateParas", templateParas); } if (null != signature && !signature.isEmpty()) { map.put("signature", signature); } return map; } } |
Receiving Status Reports
The Maven dependency to be introduced is org.springframework:spring-web:5.3.21 (example version).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { /** * Synchronize SMS receipts. */ @PostMapping("/report") public void smsHwReport(@RequestParam String smsMsgId, // Unique SMS identifier returned after an SMS is successfully sent. @RequestParam(required = false) String total, // Number of SMS segments split from a long SMS message. If the SMS message is not split, set this parameter to 1. @RequestParam(required = false) String sequence, // Sequence number after a long SMS is split. This parameter is valid only when the value of total is greater than 1. If the SMS is not split, set this parameter to 1. @RequestParam String status, // Enumerated values of an SMS status report. For details about the values, see API Reference. @RequestParam(required = false) String source, // Source of the SMS status report. 1: generated by the SMS platform. 2: returned by the SMSC. 3: generated by the cloud platform. @RequestParam(required = false) String updateTime,// SMS resource update time, which is generally the UTC time when the Message & SMS platform receives the SMS status report. The value is in the format of yyyy-MM-dd'T'HH:mm:ss'Z'. The time is converted to %3a using urlencode. // When the Message & SMS platform does not receive the SMS status report from the SMSC, the platform constructs a status report that does not contain the updateTime parameter. @RequestParam(required = false) String orgCode, // Status codes of southbound NEs are transparently transmitted. This parameter is contained only in status reports of international SMSs. // When the status code is not returned, the parameter is not used. @RequestParam(required = false) String extend, // Extended field in the request sent by a user. If the SMS sent by a user does not carry the extend parameter, the status report does not contain the extend parameter. @RequestParam(required = false) String to) { // Recipient number of the SMS corresponding to the status report. This parameter is carried only when the status report contains the extend parameter. System.out.println(" ================receive smsStatusReport ======================"); System.out.println("smsMsgId: " + smsMsgId); System.out.println("total: " + total); System.out.println("sequence: " + sequence); System.out.println("status: " + status); System.out.println("source: " + source); System.out.println("updateTime: " + updateTime); System.out.println("orgCode: " + orgCode); System.out.println("extend: " + extend); System.out.println("to: " + to); } } |
Parent topic: AK/SK Authentication (Recommended)
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
The system is busy. Please try again later.
For any further questions, feel free to contact us through the chatbot.
Chatbot