网易云信发送短信工具类
生活随笔
收集整理的這篇文章主要介紹了
网易云信发送短信工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要求:
1.賬號權限要求
您先有網易云信賬號,已經開通好了具體應用,附上了短信權限,開通好了短息模板。
這個條件就緒后,您有:
應用下申請的Appkey、網易云信分配的密鑰appSecret、短信模板TEMPLATEID
2.官方jar包
網易云信發送短信之前,需要本地項目引入其官方的jar包
以maven項目為例,具體引入環節參照:
這篇博客
引入完成后:
網易云信常用接口:發送驗證碼、校驗驗證碼、發送通知類信息。
為了滿足不同場景下使用,方便大家測試,把這三個時間整合三個獨立的,然后第四段我們整合成一個,具體用那個方便,自行選擇。
強烈推薦第四個代碼片 理由如下:
整合了發送短信消息、發送驗證碼、短信校驗碼。
修復了官方提供代碼片中過時的 DefaultHttpClient httpClient = new DefaultHttpClient();寫法。
針對有阿里代碼規范要求的做了調整。
直接粘貼復制 配參數可用!
一句話,它香啊!
【網易云信驗證碼】封裝類以及測試:
package com.項目路徑.util;import com.alibaba.fastjson.JSON; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;import java.io.IOException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** @program: auth* @description: 短信驗證碼**/ public final class SmsCodeUtil {public SmsCodeUtil() {throw new AssertionError();}//發送驗證碼的請求路徑URLprivate static final String serverUrl = "https://api.netease.im/sms/sendcode.action";//網易云信分配的賬號 private static final String appKey = "這里是一個36位的appKey";//網易云信分配的密鑰private static final String appSecret = "這里是一個12位的appSecret";//隨機數private static final String nonce = "123456";//短信模板IDprivate static final String templateid = "這里是一個12位的templateid";//驗證碼長度,范圍4~10,默認為4private static final String codelen = "4";public static String sendSmsCode(String phone) throws ClientProtocolException, IOException {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(serverUrl);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(appSecret, nonce, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", appKey);httpPost.addHeader("Nonce", nonce);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();/** 1.如果是模板短信,請注意參數mobile是有s的,詳細參數配置請參考“發送模板短信文檔”* 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']"* 3.params是根據你模板里面有幾個參數,那里面的參數也是jsonArray格式*/nvps.add(new BasicNameValuePair("templateid", templateid));nvps.add(new BasicNameValuePair("mobile", phone));nvps.add(new BasicNameValuePair("codeLen", codelen));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);/** 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500* 2.具體的code有問題的可以參考官網的Code狀態表*/String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");return code;}// 計算并獲取CheckSumprivate static String getCheckSum(String appSecret, String nonce, String curTime) {return encode("sha1", appSecret + nonce + curTime);}private static String encode(String algorithm, String value) {if (value == null) {return null;}try {MessageDigest messageDigest= MessageDigest.getInstance(algorithm);messageDigest.update(value.getBytes());return getFormattedText(messageDigest.digest());} catch (Exception e) {throw new RuntimeException(e);}}private static String getFormattedText(byte[] bytes) {int len = bytes.length;StringBuilder buf = new StringBuilder(len * 2);for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);buf.append(HEX_DIGITS[bytes[j] & 0x0f]);}return buf.toString();}private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};public static void main(String[] args) throws ClientProtocolException, IOException {sendSmsCode("155*******0");} }【網易云信校驗驗證碼】封裝類以及測試:
package com.項目路徑.util;import com.alibaba.fastjson.JSON; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients;import java.io.IOException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** @program: auth* @description: 短信驗證碼校驗**/ public final class SmsVerifyCodeUtil {public SmsVerifyCodeUtil() {throw new AssertionError();}//校驗驗證碼的請求路徑URLprivate static final String serverUrl = "https://api.netease.im/sms/verifycode.action";//網易云信分配的賬號 private static final String appKey = "appKey ";//網易云信分配的密鑰private static final String appSecret = "appSecret ";//隨機數private static final String nonce = "123456";public static String checkMsg(String phone, String sum) throws ClientProtocolException, IOException {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(serverUrl);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(appSecret, nonce, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", appKey);httpPost.addHeader("Nonce", nonce);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("mobile", phone));nvps.add(new BasicNameValuePair("code", sum));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);/** 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500* 2.具體的code有問題的可以參考官網的Code狀態表*/String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");System.out.println(code);if (code.equals("200")) {return "success";}return "error";}// 計算并獲取CheckSumprivate static String getCheckSum(String appSecret, String nonce, String curTime) {return encode("sha1", appSecret + nonce + curTime);}private static String encode(String algorithm, String value) {if (value == null) {return null;}try {MessageDigest messageDigest= MessageDigest.getInstance(algorithm);messageDigest.update(value.getBytes());return getFormattedText(messageDigest.digest());} catch (Exception e) {throw new RuntimeException(e);}}private static String getFormattedText(byte[] bytes) {int len = bytes.length;StringBuilder buf = new StringBuilder(len * 2);for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);buf.append(HEX_DIGITS[bytes[j] & 0x0f]);}return buf.toString();}private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};public static void main(String[] args) throws ClientProtocolException, IOException {checkMsg("15502293820", "7559");}}【網易云信短息通知信息】封裝類以及測試:
package com.項目路徑.util;import com.alibaba.fastjson.JSON; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;import java.io.IOException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** @program: auth* @description: 短信通知類**/ public final class SmsMsgUtil {public SmsMsgUtil() {throw new AssertionError();}//發送短信通知的請求路徑URLprivate static final String serverUrl = "https://api.netease.im/sms/sendtemplate.action";//網易云信分配的賬號 private static final String appKey = "appKey ";//網易云信分配的密鑰private static final String appSecret = "appSecret";//隨機數private static final String nonce = "123456";//短信模板IDprivate static final String templateid = "templateid ";/**** @param mobiles* 如:String mobiles="['155*******0']";* 手機號,接收者號碼列表,JSONArray格式,限制接收者號碼個數最多為100個* @param params* 如:String params="['Hi,Goods Boy']";* 短信參數列表,用于依次填充模板,JSONArray格式,每個變量長度不能超過30字,對于不包含變量的模板,不填此參數表示模板即短信全文內容* @return* @throws ClientProtocolException* @throws IOException*/public static String sendSmsMsg(String mobiles,String params) throws ClientProtocolException, IOException {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(serverUrl);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(appSecret, nonce, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", appKey);httpPost.addHeader("Nonce", nonce);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();/** 1.如果是模板短信,請注意參數mobile是有s的,詳細參數配置請參考“發送模板短信文檔”* 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']"* 3.params是根據你模板里面有幾個參數,那里面的參數也是jsonArray格式*/nvps.add(new BasicNameValuePair("templateid", templateid));nvps.add(new BasicNameValuePair("mobiles", mobiles));nvps.add(new BasicNameValuePair("params", params));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);/** 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500* 2.具體的code有問題的可以參考官網的Code狀態表*/String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");return code;}// 計算并獲取CheckSumprivate static String getCheckSum(String appSecret, String nonce, String curTime) {return encode("sha1", appSecret + nonce + curTime);}private static String encode(String algorithm, String value) {if (value == null) {return null;}try {MessageDigest messageDigest= MessageDigest.getInstance(algorithm);messageDigest.update(value.getBytes());return getFormattedText(messageDigest.digest());} catch (Exception e) {throw new RuntimeException(e);}}private static String getFormattedText(byte[] bytes) {int len = bytes.length;StringBuilder buf = new StringBuilder(len * 2);for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);buf.append(HEX_DIGITS[bytes[j] & 0x0f]);}return buf.toString();}private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};public static void main(String[] args) throws ClientProtocolException, IOException {sendSmsMsg("['155*******0']","['恭喜,你又收到我的測試短信了!']");} }【整合:網易云信 發送驗證碼、校驗驗證碼、發送短息通知信息】封裝類以及測試:
package com.項目路徑.util;import com.alibaba.fastjson.JSON; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;import java.io.IOException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** 網易云信發送短信、驗證碼、校驗驗證碼* @author zhaoxinglu*/ public final class SmsWyyxUtil {public SmsWyyxUtil() {throw new AssertionError();}/*** 網易云信分配的賬號*/private static final String APP_KEY = "APP_KEY ";/*** 網易云信分配的密鑰*/private static final String APP_SECRET = "APP_SECRET ";/*** 隨機數*/private static final String NONCE = "NONCE ";/*** 發送短息通知信息配置參數 - 請求路徑URL*/private static final String SERVER_MSG = "https://api.netease.im/sms/sendtemplate.action";/*** 發送短息通知信息配置參數 - 短信模板*/private static final String TEMPLATE_ID_MSG = "短信模板ID";/*** 發送短信驗證碼配置參數 - 請求路徑URL*/private static final String SERVER_CODE = "https://api.netease.im/sms/sendcode.action";/*** 發送短信驗證碼配置參數 - 短信模板*/private static final String TEMPLATE_ID_CODE = "短信模板ID";/*** 發送短信驗證碼配置參數 - 驗證碼長度,范圍4~10,默認為4*/private static final String CODE_LEN = "4";/*** 校驗驗證碼配置參數 - 請求路徑URL*/private static final String SERVER_VERIFY_CODE = "https://api.netease.im/sms/verifycode.action";/*** 成功值*/private static final String SUCCESS = "200";/*** 發送信息通知** @param mobiles 如:String mobiles="['15502293820']";* 手機號,接收者號碼列表,JSONArray格式,限制接收者號碼個數最多為100個* @param params 如:String params="['Hi,Goods Boy']";* 短信參數列表,用于依次填充模板,JSONArray格式,每個變量長度不能超過30字,對于不包含變量的模板,不填此參數表示模板即短信全文內容* @return true 發送成功 false失敗* @throws ClientProtocolException* @throws IOException*/public static Boolean sendSmsMsg(String mobiles, String params) throws ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(SERVER_MSG);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", APP_KEY);httpPost.addHeader("Nonce", NONCE);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("templateid", TEMPLATE_ID_MSG));nvps.add(new BasicNameValuePair("mobiles", mobiles));nvps.add(new BasicNameValuePair("params", params));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");if(SUCCESS.equals(code)) {return true;} else {return false;}}/*** 發送短信驗證碼** @param phone 發送手機號* @return true 發送成功 false失敗* @throws ClientProtocolException* @throws IOException*/public static Boolean sendSmsCode(String phone) throws ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(SERVER_CODE);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", APP_KEY);httpPost.addHeader("Nonce", NONCE);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("templateid", TEMPLATE_ID_CODE));nvps.add(new BasicNameValuePair("mobile", phone));nvps.add(new BasicNameValuePair("codeLen", CODE_LEN));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");if(SUCCESS.equals(code)) {return true;} else {return false;}}/*** 校驗驗證碼** @param phone 校驗手機號* @param sum 驗證碼* @return true 校驗成功 false校驗失敗* @throws ClientProtocolException* @throws IOException*/public static Boolean verifyCode(String phone, String sum) throws ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(SERVER_VERIFY_CODE);String curTime = String.valueOf((new Date()).getTime() / 1000L);String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);// 設置請求的headerhttpPost.addHeader("AppKey", APP_KEY);httpPost.addHeader("Nonce", NONCE);httpPost.addHeader("CurTime", curTime);httpPost.addHeader("CheckSum", checkSum);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 設置請求的的參數,requestBody參數List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("mobile", phone));nvps.add(new BasicNameValuePair("code", sum));httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 執行請求HttpResponse response = httpClient.execute(httpPost);String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");//獲取發送狀態碼String code = JSON.parseObject(responseEntity).getString("code");System.out.println("校驗發送狀態碼:" + code);if(SUCCESS.equals(code)) {return true;} else {return false;}}/*** 計算并獲取CheckSum* @param appSecret* @param nonce* @param curTime* @return*/private static String getCheckSum(String appSecret, String nonce, String curTime) {return encode("sha1", appSecret + nonce + curTime);}private static String encode(String algorithm, String value) {if (value == null) {return null;}try {MessageDigest messageDigest= MessageDigest.getInstance(algorithm);messageDigest.update(value.getBytes());return getFormattedText(messageDigest.digest());} catch (Exception e) {throw new RuntimeException(e);}}private static String getFormattedText(byte[] bytes) {int len = bytes.length;StringBuilder buf = new StringBuilder(len * 2);for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);buf.append(HEX_DIGITS[bytes[j] & 0x0f]);}return buf.toString();}private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};public static void main(String[] args) throws ClientProtocolException, IOException {//測試發送通知信息//sendSmsMsg("['155*******0']","['恭喜,你又收到我的測試短信了!']");//測試發送驗證碼//sendSmsCode("155*******0");//測試校驗驗證碼verifyCode("155*******0", "7559");}}總結
以上是生活随笔為你收集整理的网易云信发送短信工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端根据后端数据生成表格 行列合并 指定
- 下一篇: ArcGIS | 02小技巧-三调地类转