NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

More languages

How to solve Cloudflare Turnstile in Java

In Java test suites and RPA jobs, Turnstile usually appears inside a Selenium session. This guide reads the widget with Selenium, gets a token over HTTP at $0.84 per 1,000, and completes the form in the same browser.

Where Turnstile shows up in Selenium

When Selenium opens a page with Turnstile, the widget renders in an iframe from challenges.cloudflare.com. Under automation, it often stays on "Verifying" or asks for a click that does not resolve, and the form's hidden cf-turnstile-response input stays empty. Clicking into the frame from WebDriver rarely helps. The dependable path is to read the widget's site key from the main page, request a token from the API, and write it into that hidden input yourself.

You need Java 17 or newer, Selenium 4 (org.seleniumhq.selenium:selenium-java) and org.json (org.json:json) for the small amount of JSON handling. Selenium Manager, included in Selenium 4.6 and later, downloads a matching ChromeDriver automatically.

A minimal API client with org.json

This client is synchronous on purpose: a Selenium test is already sequential, so a plain loop with Thread.sleep is the clearest fit.

import java.net.URI;
import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers; import java.time.Duration; import org.json.JSONObject;

public final class TurnstileTokens {
    private final HttpClient net = HttpClient.newHttpClient();
    private final String clientKey;

    public TurnstileTokens(String clientKey) { this.clientKey = clientKey; }

    private JSONObject send(String route, JSONObject body) throws Exception {
        body.put("clientKey", clientKey);
        String raw = body.toString();
        HttpRequest rq = HttpRequest.newBuilder(URI.create("https://gatesolver.com/" + route))
            .timeout(Duration.ofSeconds(25)).header("Content-Type", "application/json")
            .POST(BodyPublishers.ofString(raw))
            .build();
        JSONObject reply = new JSONObject(net.send(rq, HttpResponse.BodyHandlers.ofString()).body());
        if (reply.optInt("errorId") != 0) {
            throw new IllegalStateException(route + " -> " + reply.optString("errorCode"));
        }
        return reply;
    }

    public String solve(String pageUrl, String siteKey, String action, String cdata) throws Exception {
        JSONObject task = new JSONObject().put("type", "AntiTurnstileTaskProxyLess")
            .put("websiteURL", pageUrl).put("websiteKey", siteKey);
        if (action != null || cdata != null) {
            task.put("metadata", new JSONObject().putOpt("action", action).putOpt("cdata", cdata));
        }
        String id = send("createTask", new JSONObject().put("task", task)).get("taskId").toString();
        long stopAt = System.nanoTime() + Duration.ofSeconds(125).toNanos();
        while (System.nanoTime() < stopAt) {
            Thread.sleep(3000);
            JSONObject st = send("getTaskResult", new JSONObject().put("taskId", id));
            switch (st.optString("status")) {
                case "ready" -> { return st.getJSONObject("solution").getString("token"); }
                case "failed" -> throw new IllegalStateException("Turnstile task failed, not charged");
                default -> { }
            }
        }
        throw new IllegalStateException("no Turnstile token within the time limit");
    }
}

putOpt skips null values, so metadata contains only what the page actually set. Reading taskId with toString() works whether the reply carries it as a string or a number.

Wait for the widget and read its attributes

Turnstile often renders a moment after the page loads. WebDriverWait waits for the container instead of failing on a race. Read attributes with getDomAttribute, which returns the value as written in the HTML.

import java.time.Duration; import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriver browser = new ChromeDriver();
try {
    String signup = "https://staging.example.com/signup";
    browser.get(signup);
    WebElement holder = new WebDriverWait(browser, Duration.ofSeconds(15))
        .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".cf-turnstile[data-sitekey]")));
    String siteKey = holder.getDomAttribute("data-sitekey");
    String action = holder.getDomAttribute("data-action");
    String cdata = holder.getDomAttribute("data-cdata");
    String callback = holder.getDomAttribute("data-callback");

    browser.findElement(By.name("email")).sendKeys("qa+signup@example.com");
    browser.findElement(By.name("password")).sendKeys(System.getenv("STAGING_TEST_PASS"));

    String token = new TurnstileTokens(System.getenv("GATESOLVER_KEY"))
        .solve(browser.getCurrentUrl(), siteKey, action, cdata);
    fillTurnstile((JavascriptExecutor) browser, token, callback);
    browser.findElement(By.cssSelector("form button[type=submit]")).click();
} finally {
    browser.quit();
}

The visible fields are filled before the solve, so the token is used within seconds of being issued. Doing it the other way round wastes part of the token's short life on typing.

Fill the field and fire the callback

Write the token into every cf-turnstile-response input (some pages render more than one form). If the widget declares a callback, call it, because many pages enable the submit button only from there.

static void fillTurnstile(JavascriptExecutor js, String token, String callback) {
    js.executeScript(
        "const t = arguments[0], cb = arguments[1];" +
        "document.querySelectorAll('input[name=\"cf-turnstile-response\"]').forEach(el => { el.value = t; });" +
        "if (cb && typeof window[cb] === 'function') window[cb](t);",
        token, callback);
}

Passing the token and callback name as script arguments avoids building JavaScript by string concatenation, which would break on quotes and is harder to read.

Widgets rendered with turnstile.render

If there is no .cf-turnstile element, the page calls turnstile.render(container, {sitekey: ...}) from its own script. Find the key in the page source or the scripts tab, or capture the options with an init script; the guide to finding Turnstile parameters covers both. The callback in that case is the function passed as the callback option, often not on window; submitting the form with the filled hidden input usually works anyway.

Using it in JUnit

Wrap the driver in a JUnit 5 extension or a @BeforeEach method, and create one TurnstileTokens per test class. Tag the tests that solve so you can run them separately from fast unit tests; each solve takes a few seconds, usually under 3 seconds, and spends a little balance. For pure UI tests of your own site, a cheaper option is to configure your staging Turnstile widget with Cloudflare's published testing site keys, and use real solves only for end to end runs against the production setup.

When the form still fails

  • Token too old. Make the solve the last thing before the click.
  • Page reloaded. A reload renders a new widget and drops the token you filled.
  • Wrong metadata. If the widget sets data-action or data-cdata, pass them; a mismatch can be refused.
  • Full page check. A "Just a moment" interstitial is the Cloudflare challenge page, which needs Cloudflare Challenge and a proxy instead.
Selenium plus a solver is meant for testing your own sign up and contact flows and for RPA on systems where you hold the account.

Headless runs in CI

CI pipelines usually run Chrome headless. Add --headless=new to the ChromeOptions so Chrome uses its current headless mode, which behaves like the normal browser. Set an explicit window size, because the default headless viewport is small and some forms lay out differently. Store the API key and test passwords as CI secrets and read them with System.getenv, as the example does. Because the Turnstile token comes from the API, headless mode makes no difference to the solve itself.

Keeping the solve and the session together

The token is accepted from your browser because the task is proxyless and Turnstile tokens are not bound to an IP. You therefore do not need to route Selenium through any particular network for this type. If your tests also meet the full page Cloudflare challenge, that is different: the cookie it returns is tied to an IP, so the task and the browser must share a proxy.

Page objects

In a page object model, give the signup page object a method such as completeTurnstile(TurnstileTokens solver) that reads the attributes, solves and fills the field. Tests then read naturally, and the Turnstile details live in one place when the page changes.

Logging what happened

When a test fails after the solve, it helps to know which step broke. Log the task id, the site key and the time between receiving the token and clicking submit. Take a screenshot with TakesScreenshot right after the click. Together these show whether the token arrived, whether it was used in time, and what the page displayed afterwards, which usually points straight at the cause.

Common questions

Why not click the Turnstile checkbox with Selenium?

The decision is made inside a cross origin frame from background signals, so automated clicks rarely pass. Filling a token is dependable.

Is getDomAttribute available in my Selenium version?

It was added in Selenium 4. On Selenium 3, getAttribute returns the same value for these data attributes.

Can I use Jackson instead of org.json?

Yes. The JSON handling is a few lines; any library that builds and reads objects works the same way.

Does the browser need a proxy for this task?

No. The Turnstile task is proxyless and the token is accepted from your Selenium browser.

How do I test without spending balance?

On your own staging site, use Cloudflare testing site keys for UI tests and run real solves only in end to end suites.

Keep reading