Send SMS with Java
A small client class on top of java.net.http.HttpClient, available since Java 11. No external libraries.
The client
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;
public class BudgetSms {
private static final String BASE = "https://api.budgetsms.net/";
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
private final Map<String, String> auth = new LinkedHashMap<>();
public BudgetSms(String username, String userid, String handle) {
auth.put("username", username);
auth.put("userid", userid);
auth.put("handle", handle);
}
/** Thrown when the API answers ERR <code>; see the error code list. */
public static class BudgetSmsException extends Exception {
public final String code;
BudgetSmsException(String code) { super("BudgetSMS error " + code); this.code = code; }
}
/** Calls sendsms, testsms, checkcredit, np, hlr or checksms and returns the text after "OK ". */
public String call(String endpoint, Map<String, String> params) throws Exception {
StringBuilder query = new StringBuilder();
Map<String, String> all = new LinkedHashMap<>(auth);
all.putAll(params);
for (Map.Entry<String, String> e : all.entrySet()) {
query.append(query.length() == 0 ? '?' : '&')
.append(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8)).append('=')
.append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8));
}
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + endpoint + "/" + query))
.timeout(Duration.ofSeconds(20)).GET().build();
String body = http.send(request, HttpResponse.BodyHandlers.ofString()).body().trim();
if (!body.startsWith("OK")) {
throw new BudgetSmsException(body.startsWith("ERR ") ? body.substring(4) : body);
}
return body.length() > 3 ? body.substring(3) : "";
}
}
Send an SMS
BudgetSms sms = new BudgetSms(System.getenv("BUDGETSMS_USERNAME"), System.getenv("BUDGETSMS_USERID"), System.getenv("BUDGETSMS_HANDLE"));
try {
String result = sms.call("sendsms", Map.of("from", "BudgetSMS", "to", "31612345678", "msg", "Hello from BudgetSMS"));
long smsId = Long.parseLong(result.split(" ")[0]); // keep it for the delivery report
System.out.println("sent, message id " + smsId);
} catch (BudgetSms.BudgetSmsException e) {
System.out.println("not sent: " + e.code);
}
Use "testsms" while developing: same parameters and answer format, but it is a simulator: no SMS is sent and nothing is charged, the message id and price in the answer are random, and about one in five calls returns a random ERR 2xxx so your error handling gets exercised (the destination number is not checked). Add "price", "1", "mccmnc", "1" or "credit", "1" to the map to get the price and number of parts, the receiver's network or your remaining credit after the message id.
Credit, number lookup and delivery status
double credit = Double.parseDouble(sms.call("checkcredit", Map.of())); // 123.455
String[] network = sms.call("np", Map.of("to", "31612345678")).split(" "); // ["204", "08", "0.0640"]
int status = Integer.parseInt(sms.call("checksms", Map.of("smsid", "64354593"))); // 1 = delivered; see the DLR status list
Delivery reports are best received with Push DLR: a GET request to your URL with the parameters id, status and date, which any servlet or Spring controller can handle. Answer with HTTP 200.