How to Build a Java SMS Verification Service with Random Codes and HTTP Calls
This guide walks through building a Java SMS verification service, covering code generation, API integration, session handling, and a reusable HTTP utility with full source examples, including Maven dependency setup, configuration file preparation, and step‑by‑step execution.
1Construct mobile verification code: use Random to generate a 4‑digit number between 1000 and 9999. 2 Send the phone number and code to an SMS platform via its API (parameters: target phone, code, optional expiration, API URL, token). 3 Store the platform’s JSON response as an object. 4 Save phone‑number, code and timestamp in the session for later validation. 5 Receive the user‑entered code and other data. 6 Compare the submitted code with the session value and check its validity period. 7 If the code matches and is within the time window, allow the request to proceed.
1. Add the required JAR
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>Below is a sample config file that stores parameters needed for the SMS service.
2. Implement an HTTP request utility
public class HttpUtil {
/** Construct common parameters timestamp, sig and respDataType */
public static String createCommonParam() {
// timestamp
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
// signature
String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);
return "timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
}
/** POST request */
public static String post(String url, String body) {
System.out.println("url:" + System.lineSeparator() + url);
System.out.println("body:" + System.lineSeparator() + body);
String result = "";
try {
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
boolean firstLine = true;
while ((line = in.readLine()) != null) {
if (firstLine) {
firstLine = false;
} else {
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** Callback test method */
public static String postHuiDiao(String url, String body) {
String result = "";
try {
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
boolean firstLine = true;
while ((line = in.readLine()) != null) {
if (firstLine) {
firstLine = false;
} else {
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}3. Generate a four‑digit random code
public static String runNumber() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder(4);
for (int i = 0; i < 4; i++) {
char ch = chars.charAt(new Random().nextInt(chars.length()));
sb.append(ch);
}
System.out.println(sb.toString());
return sb.toString();
}4. Send the verification SMS
public class IndustrySMS {
private static String operation = "/industrySMS/sendSMS";
private static String accountSid = Config.ACCOUNT_SID;
private static String to = "15342349382";
private static String smsContent = "【小陶科技】登录验证码:{" + runNumber() + "},如非本人操作,请忽略此短信。";
/** Send verification code */
public static void execute() {
String tmpSmsContent = null;
try {
tmpSmsContent = URLEncoder.encode(smsContent, "UTF-8");
} catch (Exception e) { }
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + to + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
