Java captcha solver: an API client with HttpClient
A Java captcha solver can be written with the JDK alone since Java 11, whose java.net.http.HttpClient sends the request without any library. With ilovecaptcha the client makes two HTTPS calls, createTask then getTaskResult, and builds its JSON as strings. This page explains the request, the image, the polling loop and the reading of the reply, then gives the complete class.
Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.
How do you call a captcha solver API from Java?
With java.net.http.HttpClient, part of the JDK since Java 11. The method post assembles the JSON body as a string that starts with clientKey, builds an HttpRequest with the header Content-Type: and a timeout of 30 seconds, sends it with HTTP.send and returns the reply as a String. No Maven or Gradle dependency is involved.
| Item | Value |
|---|---|
| Runs on | Java 11 or newer |
| Libraries to add | None: JDK only |
| File | Solve.java |
| Command | java Solve.java |
| HTTP client | java.net.http.HttpClient |
How do you send the captcha image and wait for the answer in Java?
Files.readAllBytes loads the image and Base64.getEncoder turns it into a string, inserted in the JSON of the task. solve posts the task to createTask, reads taskId, then calls getTaskResult after each Thread.sleep until status is ready.
POLL_INTERVALis aDurationof 1500 milliseconds.TIMEOUTis aDurationof 120 seconds: past that,solvethrows aRuntimeException.- The deadline is measured with
System.nanoTime, which does not follow clock changes. - A reply already
readyatcreateTaskis returned at once.
How does the Java example read JSON without a library, and report errors?
The JDK has no JSON parser, so the example reads what it needs with two small methods: field extracts one value with a regular expression, and object returns the solution object by counting braces. That is enough for the flat replies of the API; in a project that already uses Jackson or Gson, parse the reply with it instead. When errorId is not 0, post throws a RuntimeException with errorCode and errorDescription. Read the key with System.getenv, from a variable such as ILOVECAPTCHA_KEY.
What does a complete Java captcha solver client look like?
The class below is the whole client, in 75 lines. Solve holds the methods post, field, object, solve and getBalance, and its main reads captcha.png, submits it as an aws-waf task and prints the solution. Replace YOUR_API_KEY and YOUR_API_URL with your own values and adapt the JSON of the task to your captcha before you run it.
Solve.java · Complete Java client: one createTask call, then getTaskResult until the task is ready (preview format).import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solve {
static final String API_KEY = "YOUR_API_KEY";
static final String BASE_URL = "YOUR_API_URL";
static final Duration POLL_INTERVAL = Duration.ofMillis(1500);
static final Duration TIMEOUT = Duration.ofSeconds(120);
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
static String post(String route, String fields) throws Exception {
String body = "{\"clientKey\":\"" + API_KEY + "\"" + (fields.isEmpty() ? "" : "," + fields) + "}";
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + route))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
String result = HTTP.send(request, HttpResponse.BodyHandlers.ofString()).body();
String errorId = field(result, "errorId");
if (errorId != null && !errorId.equals("0")) {
throw new RuntimeException(field(result, "errorCode") + ": " + field(result, "errorDescription"));
}
return result;
}
static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|[^,}\\s]+)").matcher(json);
if (!m.find()) return null;
return m.group(2) != null ? m.group(2) : m.group(1);
}
static String object(String json, String name) {
int start = json.indexOf("\"" + name + "\"");
if (start < 0) return null;
start = json.indexOf('{', start);
int depth = 0;
for (int i = start; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '{') depth++;
if (c == '}' && --depth == 0) return json.substring(start, i + 1);
}
return null;
}
static String solve(String taskJson) throws Exception {
String result = post("/createTask", "\"task\":" + taskJson);
if ("ready".equals(field(result, "status"))) return object(result, "solution");
String taskId = field(result, "taskId");
long deadline = System.nanoTime() + TIMEOUT.toNanos();
while (System.nanoTime() < deadline) {
Thread.sleep(POLL_INTERVAL.toMillis());
result = post("/getTaskResult", "\"taskId\":" + taskId);
if ("ready".equals(field(result, "status"))) return object(result, "solution");
}
throw new RuntimeException("task " + taskId + " not ready after " + TIMEOUT.toSeconds() + " s");
}
static String getBalance() throws Exception {
return field(post("/getBalance", ""), "balance");
}
public static void main(String[] args) throws Exception {
String image = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("captcha.png")));
System.out.println(solve("{\"type\":\"aws-waf\",\"image\":\"" + image + "\"}"));
System.out.println(getBalance());
}
}
Java captcha solver: frequently asked questions
Do I need a Maven dependency or an SDK to solve captchas in Java?
No. Everything the client uses ships with the JDK: HttpClient for the two calls, Base64 for the image, java.util.regex to read the reply, Thread.sleep for the wait. The class on this page is the complete client. Add it to your sources as it is: the pom.xml or build.gradle of your project does not change, and there is no artifact to keep up to date.
Can I run the Java example without compiling it first?
Yes, from Java 11: the java launcher accepts a single source file, compiles it in memory and runs its main method, which is what the command java Solve.java does. For a build with several classes, compile with javac as usual, or add the class to your Maven or Gradle project. It has no dependency to declare, since HttpClient, Base64 and the regular expressions all come from the JDK.
What does solve return in Java, and how do you read it?
A String that holds the solution object as JSON text, for instance an object with a points array. The example prints it as it is. To use the values, pass that string to the JSON library of your project and map it to a class, or read a single value with the field method of the example: applied to the solution of a token task with the name token, it returns the token.
Sources
The facts and figures quoted on this page come from these sources.
- Oracle, Class HttpClient, Java SE 11 API documentation (HttpRequest, BodyPublishers, send).
- OpenJDK, JEP 330: Launch Single-File Source-Code Programs (running a source file with the java launcher, Java 11).