Send SMS from Java with HttpClient, through your own phone
Java 11's HttpClient sends the text and your phone does the rest. Then records with Gson, delivery status, retries that can't double-text, and a webhook on the JDK's own HTTP server, all run on Java 21.
Sparetext
8 min read · Nov 11, 2026
Java has had a decent HTTP client in the box since Java 11, but most SMS tutorials still start with adding a vendor SDK to your pom.xml, then buying a number, then registering it with US carriers. If your texts go to people who already know you, you can skip all of that.
Sparetext turns the Android phone you already own into an SMS gateway with a plain HTTP API. Your Java code talks to our server, and the text goes out from your phone, on your number. Every sample below ran on 11 November on Java 21, against a test copy of Sparetext with a simulated phone on the other end. No build tool needed to try them: since Java 11, java Send.java compiles and runs a single file.
What you need
- A Sparetext account. Free is 1 phone and 300 texts a month.
- An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac (the iPhone guide).
- An API key from the API keys page:
export SPARETEXT_API_KEY=spt_live_... - Java 17 or later for the records and text blocks below (we ran 21). For the second part, Gson:
com.google.code.gson:gson:2.13.2in Maven or Gradle, or the jar on the classpath.
Send your first text
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Send {
public static void main(String[] args) throws Exception {
String json = """
{"to": "+12025550191", "text": "Your table for 2 is ready. See you soon!"}
""";
HttpRequest request = HttpRequest.newBuilder(URI.create("https://sparetext.dev/api/v1/messages"))
.header("x-api-key", System.getenv("SPARETEXT_API_KEY"))
.header("content-type", "application/json")
.timeout(Duration.ofSeconds(15))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
}
}Put your own number in to, with its country code, and run java Send.java. Ours printed 202 and the JSON answer: a batchId, then the message with its id and "status":"queued". Your phone sends the text a moment later. With a bad key it printed 401 and {"error":{"code":"unauthorized","message":"That key or token is not valid. It may have been revoked."}}.
HttpClient.send throws only when the network fails; a 401 or a 500 is a normal response, so the status code is yours to check. And set a timeout on the request: without one, a stuck connection waits forever.
Records, Gson and one method for every call
The JDK can send JSON but not read it. Gson is one small jar and maps straight onto records, so the answer becomes typed objects. This class is the rest of the post in one file; run it with java -cp gson-2.13.2.jar Sms.java:
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class Sms {
static final String API = "https://sparetext.dev/api/v1";
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
static final Gson GSON = new Gson();
record Message(String id, String contact, String text, String status, String deviceName, String error) {}
record Batch(String batchId, List<Message> messages, String estimatedCompletionAt) {}
record One(Message message) {}
record Page(List<Message> messages) {}
/** Every error the API sends: a code to test in code, a message for people. */
static class ApiException extends RuntimeException {
final int status;
final String code;
final long retryAfter;
ApiException(int status, String code, String message, long retryAfter) {
super(status + " " + code + ": " + message);
this.status = status;
this.code = code;
this.retryAfter = retryAfter;
}
}
record ErrorBody(Detail error) {
record Detail(String code, String message) {}
}
static <T> T call(String method, String path, Object payload, Class<T> type, String... headers)
throws IOException, InterruptedException {
var builder = HttpRequest.newBuilder(URI.create(API + path))
.header("x-api-key", System.getenv("SPARETEXT_API_KEY"))
.header("content-type", "application/json")
.timeout(Duration.ofSeconds(15))
.method(method, payload == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(GSON.toJson(payload)));
if (headers.length > 0) builder.headers(headers);
HttpResponse<String> res = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() >= 400) {
ErrorBody.Detail e = GSON.fromJson(res.body(), ErrorBody.class).error();
long wait = res.headers().firstValueAsLong("retry-after").orElse(0);
throw new ApiException(res.statusCode(), e.code(), e.message(), wait);
}
return GSON.fromJson(res.body(), type);
}
/** Retries a timeout or a 429 without ever texting someone twice. */
static Batch sendText(Object payload) throws IOException, InterruptedException {
String key = UUID.randomUUID().toString(); // the same key on every try, so a retry can't send twice
for (int attempt = 1; ; attempt++) {
try {
return call("POST", "/messages", payload, Batch.class, "idempotency-key", key);
} catch (ApiException e) {
if (e.status != 429 || e.retryAfter == 0 || attempt == 4) throw e; // a bad number won't fix itself
Thread.sleep(e.retryAfter * 1000);
} catch (IOException e) {
if (attempt == 4) throw e; // timeout or network error: try again with the same key
Thread.sleep(attempt * 1000L);
}
}
}
static Message waitForDelivery(String id, Duration timeout) throws IOException, InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (true) {
Message m = call("GET", "/messages/" + id, null, One.class).message();
if (Set.of("delivered", "failed", "canceled").contains(m.status()) || System.nanoTime() > deadline) return m;
Thread.sleep(3000);
}
}
public static void main(String[] args) throws Exception {
Batch sent = sendText(Map.of("to", "+12025550192", "text", "Your order #1042 is out for delivery."));
Message first = sent.messages().get(0);
System.out.println(first.id() + " " + first.status() + " on " + first.deviceName());
Message last = waitForDelivery(first.id(), Duration.ofMinutes(2));
System.out.println(last.status() + (last.error() == null ? "" : " " + last.error()));
}
}It printed queued on Pixel 8 (simulated), then delivered about four seconds later. queued means the text is waiting for your phone; it then moves to dispatched (the phone has it), sent, and delivered if your carrier sends delivery reports, or failed with the reason in error. Some carriers never send delivery reports, so a text can rest at sent, which is why the wait has a deadline.
Why sendText keeps one key
Here's the thing about retries and SMS. If a request times out, you don't know whether the text was queued, and a blind retry can send it twice. The Idempotency-Key header fixes that: send the same key again and Sparetext hands back the first answer instead of queuing a second text, for 24 hours. That's why sendText makes the key once, outside the loop.
We checked both halves. The same key sent twice came back with the same message id, and only one text was queued. The same key with different words got 422 idempotency_mismatch. An account can make 15 send requests every 5 seconds, then hears 429 rate_limited with Retry-After in seconds; we sent 30 texts in a row through sendText and all 30 went through in 5.7 seconds, waiting as told. The one 429 without Retry-After is key_daily_limit, and it's thrown, not retried.
Text a list
Add these to the class (plus imports for Files, Path and Arrays). One request carries up to 100 people, each with their own words. The list comes from a bookings.json file, since Gson reads that straight into records:
record Booking(String name, String phone, String time) {}
static void textBookings() throws IOException, InterruptedException {
Booking[] bookings = GSON.fromJson(Files.readString(Path.of("bookings.json")), Booking[].class);
List<Map<String, String>> messages = Arrays.stream(bookings)
.map(b -> Map.of("to", b.phone(),
"text", "Hi " + b.name() + ", see you tomorrow at " + b.time() + ". Reply YES to confirm."))
.toList();
for (int start = 0; start < messages.size(); start += 100) {
var chunk = messages.subList(start, Math.min(start + 100, messages.size()));
Batch batch = sendText(Map.of("messages", chunk));
System.out.println(batch.batchId() + ": " + batch.messages().size()
+ " queued, last one out about " + batch.estimatedCompletionAt());
}
}Don't hand each text to its own thread to go faster. You'd hit the rate limit in the first second, and your phone sends about 30 texts a minute anyway, under Android's own limit. estimatedCompletionAt tells you when the last one should leave.
Get replies with a webhook
Sparetext can post each text your phone receives to your server, and the JDK ships a small HTTP server that's enough to take it. Anyone who finds the URL can post to it too, so check the X-Sparetext-Signature header first: t=1793438045,v1=9c2f…, a timestamp, then an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the webhook's secret.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Hook {
static final byte[] SECRET = System.getenv("SPARETEXT_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8);
static final Pattern STAMP = Pattern.compile("(?:^|,)t=(\\d+)");
static final Pattern SIG = Pattern.compile("v1=([0-9a-f]{64})");
static boolean fromSparetext(byte[] raw, String header) throws Exception {
if (header == null) return false;
var t = STAMP.matcher(header);
if (!t.find() || Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(t.group(1))) > 300) {
return false; // missing, or more than five minutes off: maybe a replayed request
}
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET, "HmacSHA256"));
mac.update((t.group(1) + ".").getBytes(StandardCharsets.UTF_8));
byte[] want = HexFormat.of().formatHex(mac.doFinal(raw)).getBytes(StandardCharsets.UTF_8);
var sig = SIG.matcher(header);
while (sig.find()) {
if (MessageDigest.isEqual(want, sig.group(1).getBytes(StandardCharsets.UTF_8))) return true;
}
return false;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3000), 0);
server.createContext("/hooks/sparetext", exchange -> {
try (exchange) {
byte[] raw = exchange.getRequestBody().readAllBytes(); // the bytes exactly as they arrived
boolean ok = "POST".equals(exchange.getRequestMethod())
&& fromSparetext(raw, exchange.getRequestHeaders().getFirst("X-Sparetext-Signature"));
if (ok) System.out.println(new String(raw, StandardCharsets.UTF_8));
exchange.sendResponseHeaders(ok ? 200 : 401, -1);
} catch (Exception e) {
exchange.sendResponseHeaders(500, -1);
}
});
server.start();
}
}Check the bytes before you parse anything, and compare with MessageDigest.isEqual, which takes the same time whether the first character or the last one differs, so nobody can guess a signature piece by piece. HexFormat (Java 17) saves you a hand-written hex loop. The loop over v1= values is there because for a day after you rotate the secret there are two.
We ran it with java Hook.java, added the URL on the Webhooks page with Text received ticked, and texted the simulated phone. The real signed delivery printed the event, with "text":"YES" inside; a POST without a signature got a 401. In Spring, the same check goes in a controller that takes the body as byte[]. The webhook guide has every event and how retries work.
What this can't do
A phone is the right tool for texts to people who know you: reminders, confirmations, alerts to your team, replies to customers. For login codes there's a ready-made verify endpoint, so you don't store codes yourself.
It's the wrong tool for marketing to a list that didn't ask. Carriers filter business texts sent by software even from a personal number, and the 10DLC post explains why. An iPhone can't send silently in the background the way Android can, and only Android phones get carrier delivery reports. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones (pricing).
The same steps exist for Python, Node.js, Go, PHP and Ruby. For a quick alert from a server, curl in a bash script is enough.
Try it with your own number
Make a key on the API keys page, pair your phone, and run java Send.java with your own number in to. When your pocket buzzes, move call and sendText into your app and send the first real reminder.
javasend smssms apihttpclientwebhookstutorial
Try it with the phone you have
Free for 1 phone and 300 texts a month. Pair it in about two minutes.
Responses
Sign in or create an account to respond.