How to Build a Java SMS Verification System with Spring Boot

This guide walks through the complete backend workflow for generating, sending, and validating SMS verification codes in a Spring Boot application, covering code generation, API integration, session handling, and utility classes with full Java examples.

Programmer DD
Programmer DD
Programmer DD
How to Build a Java SMS Verification System with Spring Boot

Part1 Business Process

Generate a mobile verification code using Random, e.g., a 4‑digit number between 1000 and 9999.

Send the phone number and code to an SMS platform via its API; typical parameters include target phone, code (with optional expiry), API URL, and token.

Store the API response (usually JSON) as a JSON object.

Save phone‑code and timestamp in the session for later verification.

Receive the user‑submitted code and other data.

Compare the submitted code with the session value and ensure it is within the valid time window.

If the code is correct and not expired, allow the request to proceed and process the business logic.

Part2 Add Required Dependency

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.11</version>
</dependency>

Part3 Simple SMS Verification Configuration

Write a config file to store parameters required by the SMS service (refer to the provider’s documentation for voice verification, etc.).

Part4 HTTP Request Utility Class

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 utility */
    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);
            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;
    }
}

Part5 Generate a Four‑Character Code

public static String runNumber() {
    String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuilder sb = new StringBuilder(4);
    for (int i = 0; i < 4; i++) {
        char ch = str.charAt(new Random().nextInt(str.length()));
        sb.append(ch);
    }
    System.out.println(sb.toString());
    return sb.toString();
}
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 SMS */
    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);
    }
}

The article concludes with the complete SMS verification login flow.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootCode ExampleHTTP requestSMS Verification
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.