More languages
How to solve reCAPTCHA v3 in Java
This guide builds a non blocking reCAPTCHA v3 solver for Java 17 and newer: requests go out with HttpClient.sendAsync, polls are scheduled instead of slept, and the caller receives a CompletableFuture. Tokens cost $0.70 per 1,000.
Why a non blocking design
A v3 solve spends most of its time waiting: a few seconds until the answer is ready, with a check every three seconds. In a service that handles many solves at once, a thread that sleeps through those waits is wasted. A scheduler plus CompletableFuture keeps threads free: each poll is a short task, and the future completes when the answer arrives. The calling code can then chain the site request with thenCompose or simply call join() in a script.
The code needs Java 17 or newer and Gson for JSON (com.google.code.gson:gson). Any JSON library works; Gson keeps the example short.
Before coding: the three values
From the target page, note the site key (in api.js?render=), the action (in grecaptcha.execute), and the request that carries the token (in the Network tab). Without the right action, tokens are often refused. The page action entry explains why it matters.
The async client
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration; // request timeouts
import java.util.Map;
import java.util.concurrent.*;
public final class V3Async {
private static final Gson GSON = new Gson();
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private final ScheduledExecutorService ticks = Executors.newSingleThreadScheduledExecutor();
private final String gateKey;
public V3Async(String gateKey) { this.gateKey = gateKey; }
private CompletableFuture<JsonObject> post(String method, Map<String, Object> body) {
var withKey = new java.util.HashMap<>(body);
withKey.put("clientKey", gateKey);
String payload = GSON.toJson(withKey);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://gatesolver.com/" + method))
.timeout(Duration.ofSeconds(25))
.headers("Content-Type", "application/json", "X-Client", "v3-async")
.POST(BodyPublishers.ofString(payload))
.build();
return http.sendAsync(req, BodyHandlers.ofString())
.thenApply(r -> GSON.fromJson(r.body(), JsonObject.class))
.thenApply(j -> {
if (j.get("errorId").getAsInt() != 0)
throw new CompletionException(new IllegalStateException(j.get("errorCode").getAsString()));
return j;
});
}
Errors are wrapped in CompletionException so they travel down the future chain like any other failure. The error code is kept as the message, which keeps logs readable.
Polling that completes a future
The solve method creates the task, then schedules a poll every three seconds. Each poll either completes the shared future (ready, failed, error) or does nothing and lets the next tick run. A timeout on the future ends the whole thing after 125 seconds.
public CompletableFuture<JsonObject> token(String pageUrl, String siteKey, String action) {
var done = new CompletableFuture<JsonObject>();
Map<String, Object> task = Map.of("type", "ReCaptchaV3TaskProxyLess", "websiteURL", pageUrl,
"pageAction", action, "websiteKey", siteKey);
post("createTask", Map.of("task", task)).whenComplete((made, err) -> {
if (err != null) { done.completeExceptionally(err); return; }
String id = made.get("taskId").getAsString();
ScheduledFuture<?> loop = ticks.scheduleWithFixedDelay(() ->
post("getTaskResult", Map.of("taskId", id)).whenComplete((st, e) -> {
if (e != null) done.completeExceptionally(e);
else if ("ready".equals(st.get("status").getAsString()))
done.complete(st.getAsJsonObject("solution"));
else if ("failed".equals(st.get("status").getAsString()))
done.completeExceptionally(new IllegalStateException("task failed, free"));
}), 3, 3, TimeUnit.SECONDS);
done.whenComplete((v, x) -> loop.cancel(false));
});
return done.orTimeout(125, TimeUnit.SECONDS);
}
public void close() { ticks.shutdownNow(); }
}
scheduleWithFixedDelay measures the three seconds from the end of each tick. Since a tick only starts an asynchronous request and returns, a very slow reply can overlap the next poll, which is harmless: whichever reply arrives first with a final status completes the future. When the future completes for any reason, the scheduled loop is cancelled. Polls that are still in flight at that moment simply find the future already done and have no effect.
Chaining the site request
The token goes into the request the page would have made. Because everything returns futures, the site request chains directly:
var solver = new V3Async(System.getenv().getOrDefault("GATESOLVER_KEY", "YOUR_API_KEY"));
var site = HttpClient.newBuilder().cookieHandler(new java.net.CookieManager()).build();
String status = solver.token("https://tickets.example.org/search", "6Lc_TICKETS_KEY", "search")
.thenCompose(sol -> {
String searchBody = "{\"query\":\"jazz\",\"city\":\"Lisbon\",\"rcToken\":\"" +
sol.get("gRecaptchaResponse").getAsString() + "\"}";
var call = HttpRequest.newBuilder(URI.create("https://tickets.example.org/api/search"))
.headers("Content-Type", "application/json", "User-Agent", sol.get("userAgent").getAsString())
.POST(BodyPublishers.ofString(searchBody))
.build();
return site.sendAsync(call, BodyHandlers.ofString());
})
.thenApply(r -> r.statusCode() + " " + r.body().length() + " bytes")
.exceptionally(t -> "failed: " + t.getMessage())
.join();
System.out.println(status);
solver.close();
Replace rcToken with the field name the real site uses. Building the JSON with string concatenation is fine for a demo; in real code, let Gson serialize a small record instead.
Running many solves at once
One V3Async instance can serve many concurrent solves; the single scheduler thread only fires short polls, and HttpClient is thread safe. There is no cap on concurrent tasks, but each key allows 600 requests per minute. With a poll every three seconds, about twenty concurrent solves use roughly 400 requests a minute, which leaves room. For more, hold a Semaphore and release it in whenComplete.
When the site rejects the token
- The action differs from what the page uses for this request.
- The token is older than about two minutes, or was already used once.
- The site expects cookies from a previous page load; reuse one
CookieManagerand load the page first. - The page loads
enterprise.js; use reCAPTCHA v3 Enterprise instead.
Read why reCAPTCHA tokens expire if your pipeline queues work between solving and sending.
Errors worth retrying
Inspect the cause of a failed future. ERROR_CAPTCHA_UNSOLVABLE, ERROR_SERVICE_UNAVAILABLE and a failed status are free and worth one more attempt; build that by calling token(...) again in an exceptionallyCompose stage (Java 12 and newer). ERROR_ZERO_BALANCE and ERROR_KEY_DENIED_ACCESS are not worth retrying. The full table is in the API docs.
Fitting it into a Spring or Quarkus service
Expose V3Async as a singleton bean and close it on shutdown, for example from a method annotated with @PreDestroy, so the scheduler thread does not keep the JVM alive. Controllers or jobs then call token(...) and return the future, or compose it with the rest of their reactive chain. Frameworks that work with CompletionStage accept the future directly. Read the API key from the framework's configuration system rather than from the code, and inject it through the constructor.
Observability
Add a whenComplete stage that records the elapsed time and outcome per action to your metrics library. A sudden rise in failures for one action often means the site changed its action name or started checking something new. Leave the token out of logs; the task id is enough to trace a solve.
Virtual threads as an alternative
On Java 21 and newer, a simpler design is a blocking loop running on a virtual thread per solve, which costs almost nothing while sleeping. The futures version shown here works on Java 17 and composes well with existing asynchronous code; choose whichever matches the rest of your project.
A test without the network
To test the chain logic without spending balance, extract the post method behind a small functional interface and pass a fake that returns canned JsonObject replies: a task id first, then processing, then ready. Lower the scheduler delay through a constructor argument in tests so the future completes in milliseconds. Add one fake that returns errorId: 1 and assert the future completes exceptionally with that code.
Common questions
Why not just Thread.sleep in a loop?
That works for scripts. In services with many concurrent solves, scheduled polls keep threads free while tokens are pending.
What is the minimum Java release for this code?
Java 17 or newer for var and the HttpClient features used here; orTimeout needs Java 9 and exceptionallyCompose Java 12.
Does the scheduler thread become a bottleneck?
No. It only fires short non blocking polls; the HTTP work runs in the HttpClient executor.
Can I use Jackson instead of Gson?
Yes. Replace the Gson calls with an ObjectMapper and JsonNode; the future logic stays the same.
How long does a v3 token take?
Usually under 3 seconds. The future times out after 125 seconds, since unsolved tasks fail at 120 seconds without charge.
Keep reading
- reCAPTCHA v3 solver$0.70 per 1,000 tasks, answers under 3 seconds.
- pageAction (reCAPTCHA action)The action label a page passes to grecaptcha.execute, how to locate it, and why a wrong label sinks good tokens.
- Why reCAPTCHA tokens expire and how to time themreCAPTCHA tokens last about two minutes and verify once; here is how to schedule solves so every token arrives fresh.
- API docscreateTask, getTaskResult, getBalance, error codes and the in.php format.