夢網科技--手機簡訊驗證碼實現

00潤物無聲00發表於2017-06-11

手機簡訊驗證碼挺簡單的,分為下面步驟

  1.生成一個隨機的驗證碼,儲存到快取中。

  2.使用http,使用手機號給簡訊閘道器傳送一個請求,把驗證碼傳送給使用者。

  3.使用者獲得簡訊驗證碼後,輸入到系統中,傳送請求,系統接收使用者輸入驗證碼,對比快取中的驗證碼,是否一致。一致則驗證通過。


工具類

import java.util.Random;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import cn.cuco.httpservice.HttpClientUtils;

/**
 * @ClassName:
 * @Description:
 */
public class SMSUtils {

	protected Logger logger = Logger.getLogger(this.getClass());

	public static boolean sendMessage(String mobile, String identifyCode) {
		boolean result = false;
		String userId = "使用者名稱";
		String password = "密碼";
		String pszMobis = mobile;
		String pszMsg = "正式完成簡訊驗證" + "【" + identifyCode + "】";// +
		String iMobiCount = "1";
		String pszSubPort = "*";
		String MsgId = RandomStringUtils.randomNumeric(19);
		try {
			String url = "請求閘道器"//
					+ "userId=" + userId//
					+ "&password=" + password//
					+ "&pszMobis=" + pszMobis//
					+ "&pszMsg=" + pszMsg//
					+ "&iMobiCount=" + iMobiCount//
					+ "&pszSubPort=" + pszSubPort//
					+ "&MsgId=" + MsgId;

			String responseBody = HttpClientUtils.sendGet(url, null, "UTF-8");

			if (StringUtils.isNotBlank(responseBody)) {
				String sub = responseBody.substring(74, responseBody.lastIndexOf("</string>"));
				System.out.println("擷取返回值=================" + sub);
				if (sub.length() > 15) {// 返回值長度大於15則表示成功
					result = true;
					System.out.println("驗證碼發至{}送成功" + mobile);
				} else {
					System.out.println("驗證碼發至{}失敗{}" + mobile + responseBody);
				}
			}
		} catch (Exception e) {
			System.out.println("驗證碼發至{}異常{}" + mobile + e.getMessage());

		}
		return result;
	}

	/**
	 * 產生4位隨機數(0000-9999)
	 * 
	 * @return 4位隨機數
	 */
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(10000) + "";
		int randLength = fourRandom.length();
		if (randLength < 4) {
			for (int i = 1; i <= 4 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;
	}

	public static void main(String[] args) {
		String mobile = "18333601438";
		String identifyCode = getFourRandom();
		SMSUtils.sendMessage(mobile, identifyCode);
	}
}

sendGet,使用get方式請求

	/**
	 * HTTP Get 獲取內容
	 * @param url  請求的url地址 ?之前的地址
	 * @param params  請求的引數
	 * @param charset  編碼格式
	 * @return 頁面內容
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 * @throws ParseException 
	 */
	public static String sendGet(String url, Map<String, String> params, String charset) throws ParseException, UnsupportedEncodingException, IOException {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		log.info("HTTP get 傳送的url 為>>>>>>>>>" + url);
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String value = entry.getValue();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value));
				}
			}
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
		}
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpClient httpClient;
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
		CloseableHttpResponse response = httpClient.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) {
			httpGet.abort();
			throw new RuntimeException("HttpClient,error status code :" + statusCode);
		}
		HttpEntity entity = response.getEntity();
		String result = null;
		if (entity != null) {
			result = EntityUtils.toString(entity, "utf-8");
		}
		EntityUtils.consume(entity);
		response.close();
		return result;
		
	}
	

執行測試

	public static void main(String[] args) {
		String mobile = "手機號";
		String identifyCode = getFourRandom();
		SMSUtils.sendMessage(mobile, identifyCode);
	}


使用:在使用的時候只需要替換掉程式碼中的,使用者名稱,密碼和請求的閘道器,就可以直接使用。




相關文章