reCAPTCHA
How to solve reCAPTCHA v2 in Java
Since Java 11 the JDK has its own HTTP client, so the only extra library you need is a JSON parser. This guide uses Jackson, notes the org.json alternative, and finishes with Selenium.
Libraries and versions
The example targets Java 17, the long term release most teams run today, and works unchanged on 21. Add com.fasterxml.jackson.core:jackson-databind for JSON and org.seleniumhq.selenium:selenium-java if you want the browser part. Use the current versions from Maven Central; the APIs used here have been stable for years.
The JDK client in java.net.http handles HTTP/2, timeouts and connection reuse. Create it once and share it, since each instance keeps its own connection pool.
Build the solver class
Jackson's tree model (ObjectNode and JsonNode) is a good fit for a small API like this: you build the request body field by field and read the reply with path(), which never throws on a missing field and returns a "missing node" instead.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
public final class GateSolver {
private static final URI BASE = URI.create("https://gatesolver.com/");
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build();
private final ObjectMapper mapper = new ObjectMapper();
private final String apiKey;
public GateSolver(String apiKey) { this.apiKey = apiKey; }
private JsonNode call(String method, ObjectNode body) throws Exception {
body.put("clientKey", apiKey);
HttpRequest req = HttpRequest.newBuilder(BASE.resolve(method))
.timeout(Duration.ofSeconds(30))
.header("Accept", "application/json").header("Content-Type", "application/json; charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body)))
.build();
var raw = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
JsonNode node = mapper.readTree(raw.body());
if (node.path("errorId").asInt() != 0) {
throw new GateException(node.path("errorCode").asText(), node.path("errorDescription").asText());
}
return node;
}
The public method goes in the same class, right after call():
public String recaptchaV2(String pageUrl, String siteKey) throws Exception {
ObjectNode body = mapper.createObjectNode();
body.putObject("task")
.put("type", "ReCaptchaV2TaskProxyLess")
.put("websiteURL", pageUrl)
.put("websiteKey", siteKey);
String taskId = call("createTask", body).path("taskId").asText();
long deadline = System.nanoTime() + Duration.ofSeconds(125).toNanos();
while (System.nanoTime() < deadline) {
Thread.sleep(3_000);
JsonNode r = call("getTaskResult", mapper.createObjectNode().put("taskId", taskId));
String status = r.path("status").asText();
if ("ready".equals(status)) return r.path("solution").path("gRecaptchaResponse").asText();
if ("failed".equals(status)) throw new GateException("FAILED", "not charged");
}
throw new GateException("TIMEOUT", "no token after 125 s");
}
}
GateException is a plain checked exception with a code field, defined in a few lines next to the class. Keeping the API's error code as a separate field, rather than burying it in the message, is what makes selective retries simple later.
The org.json alternative
If your project already uses org.json, swap the tree model: build the body with new JSONObject().put("task", new JSONObject().put("type", ...)) and read replies with new JSONObject(responseBody).optString("status"). The opt methods mirror Jackson's path() and return defaults instead of throwing. Choose whichever library is already on the classpath; there is no reason to carry both.
Using a virtual thread per solve
On Java 21, Thread.sleep inside a virtual thread does not hold a platform thread, so you can run hundreds of solves with Executors.newVirtualThreadPerTaskExecutor() and keep the simple blocking style shown above. On Java 17, use a fixed thread pool sized to the number of forms you actually submit at once. Either way, the API has no limit on concurrent tasks, only a rate limit of 600 requests per minute per key.
Place the token with JavascriptExecutor
Selenium's JavascriptExecutor passes Java values into a script through arguments. Fill the hidden response field, then submit.
WebDriver driver = new ChromeDriver();
try {
String formUrl = "https://example.com/quote-request";
driver.get(formUrl);
String siteKey = driver.findElement(By.cssSelector("[data-sitekey]")).getDomAttribute("data-sitekey");
GateSolver solver = new GateSolver(System.getenv("GATE_KEY"));
String token = solver.recaptchaV2(formUrl, siteKey);
((JavascriptExecutor) driver).executeScript(
"document.querySelectorAll('[name=\"g-recaptcha-response\"]').forEach(t => t.value = arguments[0]);",
token);
driver.findElement(By.cssSelector("form [type=submit]")).click();
new WebDriverWait(driver, Duration.ofSeconds(15)).until(ExpectedConditions.urlContains("thank"));
} finally {
driver.quit();
}
Setting every matching field covers pages that render the widget twice, for example in a desktop and a mobile layout. The final wait checks for a thank you URL; adapt it to whatever your form shows after a good submit. Calling quit() in finally makes sure a failed solve never leaves a Chrome process running on the build agent.
Reading the site key without a browser
When you only need the key, or the whole flow can run without JavaScript, jsoup is the lightest option in Java. Jsoup.connect(url).get() returns a parsed document, and doc.selectFirst("[data-sitekey]").attr("data-sitekey") gives you the value. The same document holds the form's hidden inputs, so you can collect them with doc.select("form input[type=hidden]") and post everything with the JDK client using BodyPublishers.ofString() and an application/x-www-form-urlencoded body. Remember to URL encode each value with URLEncoder.encode(value, StandardCharsets.UTF_8).
If jsoup finds no data-sitekey, the page builds the widget from a script and you will need the browser, or the techniques in the guide on how to find the reCAPTCHA site key.
Testing the solver class
Because the base address is a single constant, it is easy to make it a constructor parameter and point the class at a stub server in tests. WireMock, or the small com.sun.net.httpserver.HttpServer that ships with the JDK, can return a fixed task id from /createTask and a ready reply from /getTaskResult. Add cases for an error reply and for a task that stays in processing, and make the poll interval and deadline parameters too so the timeout test runs in milliseconds rather than two minutes.
Retries and logging
Retry only ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE, at most twice, with a pause of a few seconds. Neither costs anything. Other codes point to a fix on your side: ERROR_INVALID_TASK_DATA names the missing field in its description, ERROR_ZERO_BALANCE needs a top-up, and ERROR_KEY_DENIED_ACCESS means the key in your environment is not the account's current one.
Log the task id with SLF4J or your logger of choice at debug level for each solve. If a site starts rejecting tokens, the ids let you check timing between solve and submit. Keep the gap under two minutes; the article on token expiry explains why that window is fixed.
One more lever exists when tokens are refused even though they are fresh: the site may expect the solve and the submit to come from one IP. In that case add .put("proxy", "http://user:pass@host:port") to the task node, change the type to ReCaptchaV2Task, and point ChromeDriver at the same proxy through ChromeOptions. Start proxyless and switch only when you see this pattern, since a proxy adds its own latency and its own failure modes.
The task also accepts isInvisible and pageAction, listed on the reCAPTCHA v2 page. For a larger Selenium setup with grids and page objects, the Selenium integration guide goes further.
Common questions
Which Java version is required?
Java 11 or newer for java.net.http; the example is written for Java 17 and runs on 21.
Is Jackson required?
No. Any JSON library works; org.json is a common lighter choice and the guide shows how to swap it in.
Can I use OkHttp instead of the JDK client?
Yes. The API only needs JSON POST requests, so any HTTP client that can send them will work.
Do virtual threads make solving faster?
No, solve time stays the same. They let you wait on many solves at once without a large platform thread pool.
Why does the script set every g-recaptcha-response field?
Some layouts render the widget twice. Filling each matching field makes sure the one inside the submitted form has the token.
Keep reading
- SeleniumThe reference Selenium setup in Python and Java: explicit waits, reCAPTCHA v2 and Turnstile tokens, callbacks, retries and Grid scaling.
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- 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.
- SeleniumThe long standing browser automation project built on WebDriver, usable from many languages and scalable through Grid.