Implementing SMS Verification in Java Using a Third‑Party API
This article provides a step‑by‑step guide for implementing a Java‑based SMS verification system, covering random code generation, API request construction, session handling, and includes full Java code for utility classes, configuration, and sending the verification message via a third‑party service.
Hello, I am a top architect.
Below are the steps to build a simple SMS verification feature:
1. Generate a random numeric verification code (e.g., a 4‑digit number between 1000 and 9999).
2. Call the SMS provider’s API with parameters such as target phone number, the generated code (or code with expiration), API endpoint, and authentication token.
3. Store the API response (usually JSON) for further processing.
4. Save the phone number, verification code, and timestamp in the server session for later validation.
5. Receive the user‑submitted verification code and other data.
6. Compare the submitted code with the one stored in the session and ensure it is still within the valid time window.
7. If the code matches and is not expired, consider the verification successful and proceed with the business logic.
First, add the required Maven dependency for the utility library:
<!-- Maven dependency for commons‑codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>Next, create a configuration class (Config) to hold constants such as ACCOUNT_SID, AUTH_TOKEN, BASE_URL, etc. Then implement an HTTP utility class:
public class HttpUtil {
/**
* Build common parameters: timestamp, sig, and respDataType.
*/
public static String createCommonParam() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);
return "timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
}
/**
* Send a 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 {
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) {
out.write(body);
out.flush();
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
String line;
boolean firstLine = true;
while ((line = in.readLine()) != null) {
if (!firstLine) {
result += System.lineSeparator();
}
firstLine = false;
result += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Callback test method (similar to post).
*/
public static String postHuiDiao(String url, String body) {
// Implementation identical to post, omitted for brevity.
return post(url, body);
}
}Utility method to generate a random 4‑character alphanumeric string (used as verification 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();
}Finally, the class that puts everything together and sends the SMS:
public class IndustrySMS {
private static final String OPERATION = "/industrySMS/sendSMS";
private static final String ACCOUNT_SID = Config.ACCOUNT_SID;
private static final String TO = "15342349382"; // target phone number
private static final String SMS_CONTENT = "【XiaoTao Tech】Login code: {" + runNumber() + "}, ignore if not you.";
/**
* Send verification code SMS.
*/
public static void execute() {
try {
String encodedContent = URLEncoder.encode(SMS_CONTENT, "UTF-8");
String url = Config.BASE_URL + OPERATION;
String body = "accountSid=" + ACCOUNT_SID + "&to=" + TO + "&smsContent=" + encodedContent + HttpUtil.createCommonParam();
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}Running IndustrySMS.execute() will generate a code, send it via the third‑party SMS service, and print the response.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.