Quick answer
To use an OTP SMS API in Java and Android, put the SMS call in your Java backend, never in the app. A Spring Boot service generates the code with SecureRandom, stores its hash with a 5-minute expiry and sends it with Java 11 HttpClient to the SMSGatewayHub SendSMS endpoint (channel=OTP, API key, DLT entity ID and template ID). The Android app calls your backend and reads the SMS automatically with Google's SMS Retriever API, which needs no SMS permission. OTP SMS costs ₹0.185 to ₹0.245 per SMS + GST, with 2-6 second typical delivery.
Key takeaways
- Java backend sends: Java 11
HttpClient, a 10-second timeout and the JobId logged.
- Spring Boot verifies: hashed code, expiry, attempt limit and resend cooldown on the server.
- Android only talks to your backend: the API key never ships inside the APK.
- Auto-read without SMS permission: SMS Retriever API plus an 11-character app hash at the end of the message.
- DLT first: the app-hash line must be part of the approved template, or the operator rejects the SMS.
How does an OTP flow work between Android, Java and the SMS API?
| Step | Where | What happens |
| 1 | Android app | User types a mobile number; the app starts the SMS Retriever and calls POST /api/otp/send on your server. |
| 2 | Spring Boot | Generates a 6-digit code, stores its hash for 5 minutes, calls SendSMS. |
| 3 | SMSGatewayHub | DLT scrubbing and delivery on a transactional route, 2-6 seconds typical. |
| 4 | Android app | SMS Retriever hands the message to the app; the app extracts the code. |
| 5 | Spring Boot | POST /api/otp/verify compares the code with the stored hash and logs the user in. |
How do you send an OTP SMS with Java 11 HttpClient?
No extra library is needed. Build the query string with URL encoding, send a GET request and parse the JSON reply with Jackson (already in every Spring Boot web project).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class OtpSmsClient {
private static final String URL = "https://www.smsgatewayhub.com/api/mt/SendSMS";
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
private final ObjectMapper json = new ObjectMapper();
private final String apiKey, senderId, entityId, templateId;
public OtpSmsClient(String apiKey, String senderId, String entityId, String templateId) {
this.apiKey = apiKey; this.senderId = senderId; this.entityId = entityId; this.templateId = templateId;
}
/** Returns the parsed reply; ErrorCode "000" means accepted. */
public JsonNode send(String number, String text) throws Exception {
Map<String, String> p = new LinkedHashMap<>();
p.put("APIKey", apiKey); p.put("senderid", senderId);
p.put("channel", "OTP"); p.put("DCS", "0");
p.put("flashsms", "0"); p.put("number", number);
p.put("text", text); p.put("route", "1");
p.put("EntityId", entityId); p.put("dlttemplateid", templateId);
String q = p.entrySet().stream()
.map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpRequest req = HttpRequest.newBuilder(URI.create(URL + "?" + q))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
return json.readTree(res.body());
}
}
A successful reply looks like this:
{ "ErrorCode": "000", "ErrorMessage": "Success", "JobId": "20047",
"MessageData": [ { "Number": "9198XXXXXXXX", "MessageId": "..." } ] }
Keep the JobId: it links the OTP to its delivery report. The full parameter list is in the developer API docs and our OTP REST API reference.
How do you build send and verify OTP endpoints in Spring Boot?
The service below keeps codes in an in-memory map with an expiry time, for clarity. In production with more than one instance, store the same record in Redis so every node sees it.
@Service
public class OtpService {
private record Entry(String hash, long expires, int tries) {}
private final Map<String, Entry> store = new ConcurrentHashMap<>();
private final Map<String, Long> lastSend = new ConcurrentHashMap<>();
private final SecureRandom rnd = new SecureRandom();
private final OtpSmsClient sms;
private final byte[] pepper;
public OtpService(OtpSmsClient sms, @Value("${otp.pepper}") String pepper) {
this.sms = sms; this.pepper = pepper.getBytes(StandardCharsets.UTF_8);
}
private String hash(String number, String code) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(pepper, "HmacSHA256"));
return HexFormat.of().formatHex(mac.doFinal((number + ":" + code).getBytes(StandardCharsets.UTF_8)));
}
public boolean send(String number, String appHash) throws Exception {
long now = System.currentTimeMillis();
Long last = lastSend.get(number);
if (last != null && now - last < 45_000) throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS, "Wait before resending");
String code = String.valueOf(100000 + rnd.nextInt(900000));
store.put(number, new Entry(hash(number, code), now + 300_000, 0));
lastSend.put(number, now);
// text must match the approved DLT template exactly
String text = code + " is your OTP to log in to ABC App. Do not share it. - ABC\n" + appHash;
JsonNode r = sms.send(number, text);
return "000".equals(r.path("ErrorCode").asText());
}
public boolean verify(String number, String code) throws Exception {
Entry e = store.get(number);
if (e == null || System.currentTimeMillis() > e.expires()) { store.remove(number); return false; }
if (e.tries() >= 5) { store.remove(number); return false; }
boolean ok = MessageDigest.isEqual(e.hash().getBytes(StandardCharsets.UTF_8),
hash(number, code).getBytes(StandardCharsets.UTF_8));
if (ok) store.remove(number); // one use only
else store.put(number, new Entry(e.hash(), e.expires(), e.tries() + 1));
return ok;
}
}
@RestController
@RequestMapping("/api/otp")
public class OtpController {
private final OtpService otp;
public OtpController(OtpService otp) { this.otp = otp; }
@PostMapping("/send")
public Map<String, Object> send(@RequestBody Map<String, String> b) throws Exception {
String n = b.getOrDefault("number", "");
if (!n.matches("^91[6-9]\\d{9}$")) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid number");
return Map.of("ok", otp.send(n, b.getOrDefault("appHash", "")));
}
@PostMapping("/verify")
public Map<String, Object> verify(@RequestBody Map<String, String> b) throws Exception {
return Map.of("ok", otp.verify(b.getOrDefault("number", ""), b.getOrDefault("otp", "")));
}
}
Register OtpSmsClient as a @Bean that reads the API key, sender ID, entity ID and template ID from environment variables. Add a per-IP rate limit on /send (for example with Bucket4j or your API gateway) so one client cannot spray many numbers.
ℹ️In a real app do not accept the app hash from the client blindly. Hard-code your release and debug hashes on the server and send the one that matches the build, or keep a single hash in the template.
How does Android auto-read the OTP with the SMS Retriever API?
The SMS Retriever API is part of Google Play services. It lets your app receive one matching SMS for up to 5 minutes without the READ_SMS or RECEIVE_SMS permission, which Google Play restricts. The message is matched by an 11-character hash of your app that must appear in the SMS, usually on its own last line.
// build.gradle: implementation "com.google.android.gms:play-services-auth-api-phone:18.1.0"
// 1. start listening, then ask your backend to send the OTP
SmsRetriever.getClient(this).startSmsRetriever()
.addOnSuccessListener { api.sendOtp(phone) } // your Retrofit/OkHttp call to /api/otp/send
// 2. receive the message
class OtpReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != SmsRetriever.SMS_RETRIEVED_ACTION) return
val extras = intent.extras ?: return
val status = extras.get(SmsRetriever.EXTRA_STATUS) as Status
if (status.statusCode == CommonStatusCodes.SUCCESS) {
val sms = extras.getString(SmsRetriever.EXTRA_SMS_MESSAGE).orEmpty()
val code = Regex("\\b(\\d{6})\\b").find(sms)?.groupValues?.get(1)
code?.let { OtpBus.post(it) } // fill the field, then call /api/otp/verify
}
}
}
Register the receiver for SmsRetriever.SMS_RETRIEVED_ACTION with the com.google.android.gms.auth.api.phone.permission.SEND permission so only Play services can trigger it. Google documents how to compute your app hash from the signing certificate; the debug and release builds have different hashes.
If you would rather let the user confirm each code, Google's SMS User Consent API shows a one-tap prompt and does not need the hash, at the cost of one extra tap.
How do you register a DLT template that works with SMS Retriever?
Every OTP in India must match an approved DLT template word for word. If your app adds the 11-character hash but the template does not allow it, the operator blocks the message. Register the template with the hash already in it, for example:
{#numeric#} is your OTP to log in to ABC App. Do not share it. - ABC
FA+9qCX9VSu
If you use more than one hash (debug and release), register the hash line as a variable in the way your DLT operator allows, or keep separate templates. Our team checks the format during DLT registration; see also the DLT template registration process.
✔Keep the key out of the APK. An APK can be unpacked in minutes. If the SMS API key sits inside it, anyone can send SMS on your balance. The Android app should only ever call your own backend. The same rule applies to Flutter and iOS apps, covered in our
Flutter and iOS OTP guide.
Why choose SMSGatewayHub as the OTP SMS API for Java and Android?
- Plain HTTPS GET with a JSON reply: Java 11
HttpClient and Jackson are enough.
- 2-6 second typical delivery on priority transactional routes, with automatic retry and load balancing across operator routes.
- ₹0.185 to ₹0.245 per OTP SMS + 18% GST, DLT scrubbing included, pay only for delivered. See OTP SMS pricing.
- Free DLT help, including templates with an app-hash line.
- Since 2009, 99.9% uptime SLA, ISO 27001 certified.
- Passwordless option: OneTap Verify login links instead of typed codes.
Get 1,000 free SMS credits and test auto-read OTP on your Android app
No credit card. Free DLT registration help. Copy your API key into your Spring Boot config and send your first code.
Create free account
Frequently asked questions
How do I send an OTP SMS from Java?
Use Java 11 HttpClient to call https://www.smsgatewayhub.com/api/mt/SendSMS with APIKey, senderid, channel=OTP, route=1, number, text, EntityId and dlttemplateid, URL-encoded. An ErrorCode of 000 in the JSON reply means the OTP was accepted.
Can my Android app call the OTP SMS API directly?
It should not. The API key would sit inside the APK, where anyone can extract it. The app should call your own backend, and the backend calls the SMS API.
How does Android read the OTP automatically?
Use Google's SMS Retriever API. Start it before requesting the code and add your app's 11-character hash to the end of the SMS. The app then receives the message without any SMS permission.
Does the app hash need to be in the DLT template?
Yes. The SMS must match the approved DLT template exactly, so register the template with the hash line included, or as a variable if your operator allows it.
How much does an OTP SMS cost?
OTP SMS on SMSGatewayHub costs ₹0.185 to ₹0.245 per SMS plus 18% GST, depending on pack size, with DLT scrubbing included and billing only for delivered OTPs.
Related reading: OTP SMS API, verify and resend OTP flow, OTP SMS API in .NET, OTP SMS API with Node.js and React and testing your OTP API.
Sources: SMSGatewayHub OTP SMS API page and developer API documentation (November 2026); Java SE 11 HttpClient documentation; Spring Boot documentation; Google Play services SMS Retriever API and SMS User Consent API documentation; TRAI Telecom Commercial Communications Customer Preference Regulations for DLT rules. Prices exclude 18% GST and can change; confirm your rate with sales before purchase.