Integrations
Validate phone numbers and emails in Java
Check emails, phone numbers and IPs from Java with the JDK HttpClient and Jackson. A small client with timeouts, retries on rate limits and a fail-open signup check.
Updated 2026-11-23
This recipe calls the API from Java with the JDK java.net.http.HttpClient. You get an email, phone and IP check with a deadline on every call, retries that respect the rate limit and a decision that never blocks a signup because of an API problem.
What you need
- Java 17 or later, for records and the built-in HTTP client.
- Jackson (
jackson-databind) to read JSON. Any JSON library works the same way. - A Qelka API key in the
API_KEYenvironment variable. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. Add Jackson
With Maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
2. The client
package app;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public final class ValidateClient {
private static final String BASE_URL = "https://api.qelka.com/v1";
private static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503);
private static final ObjectMapper JSON = new ObjectMapper();
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
public static final class ApiException extends RuntimeException {
public final int status;
public final String type;
public final String requestId;
ApiException(int status, String type, String message, String requestId) {
super(type + ": " + message);
this.status = status;
this.type = type;
this.requestId = requestId;
}
}
private final String apiKey;
public ValidateClient(String apiKey) {
this.apiKey = apiKey;
}
public static ValidateClient fromEnvironment() {
return new ValidateClient(System.getenv("API_KEY"));
}
private JsonNode call(String path, Map<String, Object> body) throws IOException, InterruptedException {
String payload = JSON.writeValueAsString(body);
for (int attempt = 1; ; attempt++) {
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.timeout(Duration.ofSeconds(12))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 200 && status < 300) {
return JSON.readTree(response.body());
}
JsonNode error = JSON.readTree(response.body()).path("error");
String requestId = response.headers().firstValue("X-Request-Id").orElse("");
if (!RETRYABLE.contains(status) || attempt == 4) {
throw new ApiException(status, error.path("type").asText("unknown"), error.path("message").asText(""), requestId);
}
long waitMillis = (1L << (attempt - 1)) * 1000 + ThreadLocalRandom.current().nextInt(250);
String retryAfter = response.headers().firstValue("Retry-After").orElse("");
if (retryAfter.matches("\\d+") && Long.parseLong(retryAfter) > 0) {
waitMillis = Long.parseLong(retryAfter) * 1000;
}
Thread.sleep(waitMillis);
}
}
public JsonNode verifyEmail(String email) throws IOException, InterruptedException {
return call("/email", Map.of("email", email));
}
public JsonNode validatePhone(String phone, String country) throws IOException, InterruptedException {
Map<String, Object> body = new LinkedHashMap<>();
body.put("phone", phone);
if (country != null && !country.isBlank()) {
body.put("country", country);
}
return call("/phone", body);
}
public JsonNode lookupIp(String ip) throws IOException, InterruptedException {
return call("/ip", Map.of("ip", ip));
}
}
The Retry-After header wins over the backoff on a 429. An error body carries a documented type, and X-Request-Id is what support asks for first. See Errors and Rate limits.
3. Decide on a signup
package app;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.List;
public final class SignupCheck {
public record Verdict(boolean reject, List<String> reasons, boolean review, String e164) {}
private final ValidateClient client;
public SignupCheck(ValidateClient client) {
this.client = client;
}
public Verdict check(String email, String phone, String country, String ip) {
boolean reject = false;
boolean review = false;
String e164 = null;
List<String> reasons = new ArrayList<>();
try {
JsonNode result = client.verifyEmail(email);
String status = result.path("status").asText();
if (status.equals("undeliverable")) {
reject = true;
JsonNode suggestion = result.path("did_you_mean");
reasons.add(suggestion.isTextual() ? "Did you mean " + suggestion.asText() + "?" : "This email address cannot receive mail.");
} else if (status.equals("risky") && result.path("reason").asText().equals("disposable")) {
review = true;
}
} catch (Exception error) {
skipped(error);
}
try {
JsonNode result = client.validatePhone(phone, country);
String status = result.path("status").asText();
if (status.equals("invalid")) {
reject = true;
reasons.add("This phone number is not valid.");
} else if (status.equals("valid")) {
e164 = result.path("e164").asText(null);
}
} catch (Exception error) {
skipped(error);
}
if (ip != null && !ip.isBlank()) {
try {
JsonNode result = client.lookupIp(ip);
if (result.path("risk").path("level").asText().equals("high") || result.path("flags").path("tor").asBoolean()) {
review = true;
}
} catch (ValidateClient.ApiException error) {
if (!error.type.equals("unprocessable_input")) {
skipped(error);
}
} catch (Exception error) {
skipped(error);
}
}
return new Verdict(reject, reasons, review, e164);
}
private static void skipped(Exception error) {
if (error instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
if (error instanceof ValidateClient.ApiException api) {
System.err.printf("validation skipped: %s status=%d request_id=%s%n", api.type, api.status, api.requestId);
} else {
System.err.println("validation skipped: " + error.getClass().getSimpleName());
}
}
}
A failed call never sets reject: the signup goes through and you check it again later. Only a clear negative answer blocks.
4. Use it
SignupCheck signup = new SignupCheck(ValidateClient.fromEnvironment());
SignupCheck.Verdict verdict = signup.check("jane@example.com", "+14155550123", null, "8.8.8.8");
if (verdict.reject()) {
// answer 422 with verdict.reasons()
}
Store verdict.e164() instead of what was typed, and keep a review flag on the account for a person or a rule to look at.
5. What the fields mean
| Field | Value | Action |
|---|---|---|
status of an email |
undeliverable |
Reject, show did_you_mean |
status of an email |
risky |
Accept and flag, or reject disposable inboxes |
status of an email |
unknown |
Accept |
status of a phone |
valid |
Store e164 |
status of a phone |
unknown |
Send country or ask for the + format |
risk.level of an IP |
high |
Ask for extra verification |
A 422 unprocessable_input on the IP is a private or loopback address, normal in local development, so the code ignores it. For many values at once, POST /batch takes up to 100 items in one request: see the batch reference.
Handle errors and rate limits
No error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key. 402 insufficient_credits means an empty balance: alert yourself and keep failing open. A key allows 200 requests per 10 seconds, then you get 429 rate_limited. Each email check costs 1 credit.
Related
Frequently asked questions
Is there an official Java library?
Which timeout should I set on HttpClient?
Can I call the API from a virtual thread?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time