Java 實現傳送驗證碼並呼叫介面驗證 (網易雲信)
阿新 • • 發佈:2019-01-02
大概流程:
- 使用者輸入賬號點選獲取驗證碼,驗證是否繫結手機號碼,繫結則傳送驗證碼
- 使用者輸入驗證碼,呼叫介面驗證是否正確返回響應
首先我們需要在網易雲信註冊賬號,獲取得到App Key和App Secret
需要注意的幾個引數:
傳送驗證碼引數
傳送驗證碼狀態:簡訊狀態碼
簡訊驗證碼引數
簡訊驗證碼狀態:code狀態表
專案中需要的jar:
httpclient-4.5.2.jar
httpcore-4.4.4.jar
Java工具類程式碼:校驗碼生成類
package com.sima.toolcode; import java.security.MessageDigest; /** * description : 校驗碼生成類 */ public class CheckSumBuilder { //計算並獲取checkSum public static String getCheckSum(String appSecret,String nonce,String curTime){ return encode("SHA",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 sb=new StringBuilder(len*2); for(int $i=0;$i<len;$i++){ sb.append(HEX_DIGITS[(bytes[$i]>>4)&0x0f]); sb.append(HEX_DIGITS[bytes[$i]&0x0f]); } return sb.toString(); } private static final char[] HEX_DIGITS={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; }
傳送簡訊工具類
package com.sima.toolcode; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; 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; /** * description : 傳送簡訊工具類 */ public class SendMessage { private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";//請求的URL private static final String APP_KEY = "badf8***1ea0c90b";//網易雲分配的賬號 private static final String APP_SECRET = "1c88e****14e4";//密碼 private static final String MOULD_ID="39**766";//模板ID private static final String NONCE = "123456";//隨機數 //驗證碼長度,範圍4~10,預設為4 private static final String CODELEN = "6"; public static String sendMsg(String phone) throws ClientProtocolException, IOException{ CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(SERVER_URL); String curTime = String.valueOf((new Date().getTime() / 1000L)); String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime); //設定請求的header post.addHeader("AppKey", APP_KEY); post.addHeader("Nonce", NONCE); post.addHeader("CurTime", curTime); post.addHeader("CheckSum", checkSum); post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); //設定請求引數 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("templateid", MOULD_ID)); nameValuePairs.add(new BasicNameValuePair("mobile", phone)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8")); //執行請求 HttpResponse response = httpclient.execute(post); String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8"); return responseEntity; } }
檢測簡訊驗證碼工具類
package com.sima.toolcode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 com.alibaba.fastjson.JSON;
/**
* description : 檢測簡訊驗證碼工具類
*/
public class MobileMessageCheck {
private static final String SERVER_URL="https://api.netease.im/sms/verifycode.action";//校驗驗證碼的請求路徑URL
private static final String APP_KEY="badf87f8a7******bd1ea0c90b";//賬號
private static final String APP_SECRET="1c8**14e4";//金鑰
private static final String NONCE="123456";//隨機數
public static String checkMsg(String phone,String sum) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(SERVER_URL);
String curTime=String.valueOf((new Date().getTime()/1000L));
String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);
//設定請求的header
post.addHeader("AppKey",APP_KEY);
post.addHeader("Nonce",NONCE);
post.addHeader("CurTime",curTime);
post.addHeader("CheckSum",checkSum);
post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//設定請求引數
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mobile",phone));
nameValuePairs.add(new BasicNameValuePair("code",sum));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
//執行請求
HttpResponse response=httpclient.execute(post);
String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
//判斷是否傳送成功,傳送成功返回true
String code= JSON.parseObject(responseEntity).getString("code");
if (code.equals("200")){
return "success";
}
return "error";
}
}
傳送返回狀態解析
//data為傳送驗證碼返回標識,這裡只判斷常用的幾種狀態
var m = data.split(",");
var code = m[0].split(":")[1];
obj = (m[2].split(":")[1]).replace("}", "");
if (code == "200") {
alert("驗證碼已發到" + phone + "號碼中,請查收");
} else if (code == "315") {
alert("您繫結的手機號" + phone + "IP限制;");return;
} else if (code == "301") {
alert("您繫結的手機號" + phone + "被封禁!");return;
} else if (code == "403") {
alert("您繫結的手機號" + phone + "非法操作或沒有許可權!");return;
} else if (code == "404") {
alert("您繫結的手機號" + phone + "物件不存在!");return;
} else if (code == "414") {
alert("您繫結的手機號" + phone + "引數錯誤!");return;
} else if (code == "500") {
alert("您繫結的手機號" + phone + "伺服器內部錯誤!");return;
} else if (code == "408") {
alert("您繫結的手機號" + phone + "客戶端請求超時!");return;
} else if (code == "419") {
alert("您繫結的手機號" + phone + "數量超過上限!");return;
}