API Tutorials

Java CompletableFuture + CaptchaAI: Async CAPTCHA Pipeline

Java's CompletableFuture provides a compositional async API — chain submission, polling, and result handling without blocking threads. This tutorial builds a parallel CAPTCHA solving pipeline using CaptchaAI's API.

Prerequisites

<!-- pom.xml — only standard library needed -->
<!-- Java 11+ for HttpClient -->
<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

<!-- Optional: Gson for JSON parsing -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

CaptchaAI Client

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class CaptchaAiClient {

    private static final String SUBMIT_URL = "https://ocr.captchaai.com/in.php";
    private static final String RESULT_URL = "https://ocr.captchaai.com/res.php";

    private final HttpClient httpClient;
    private final ScheduledExecutorService scheduler;
    private final Gson gson;
    private final String apiKey;

    public CaptchaAiClient(String apiKey) {
        this.apiKey = apiKey;
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(30))
                .build();
        this.scheduler = Executors.newScheduledThreadPool(4);
        this.gson = new Gson();
    }

    public CompletableFuture<String> solveCaptcha(String sitekey, String pageurl) {
        return submitTask(sitekey, pageurl)
                .thenCompose(this::pollResult);
    }

    private CompletableFuture<String> submitTask(String sitekey, String pageurl) {
        String body = buildFormData(Map.of(
                "key", apiKey,
                "method", "userrecaptcha",
                "googlekey", sitekey,
                "pageurl", pageurl,
                "json", "1"
        ));

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(SUBMIT_URL))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

        return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(resp -> {
                    JsonObject json = gson.fromJson(resp.body(), JsonObject.class);
                    if (json.get("status").getAsInt() != 1) {
                        throw new RuntimeException(
                                "Submit failed: " + json.get("request").getAsString());
                    }
                    return json.get("request").getAsString(); // captcha ID
                });
    }

    private CompletableFuture<String> pollResult(String captchaId) {
        CompletableFuture<String> result = new CompletableFuture<>();

        scheduler.schedule(
                () -> doPoll(captchaId, result, 0),
                5, TimeUnit.SECONDS
        );

        return result;
    }

    private void doPoll(String captchaId, CompletableFuture<String> result,
                        int attempt) {
        if (attempt >= 60) {
            result.completeExceptionally(
                    new RuntimeException("Timeout after 300s"));
            return;
        }

        String url = String.format(
                "%s?key=%s&action=get&id=%s&json=1",
                RESULT_URL, apiKey, captchaId
        );

        httpClient.sendAsync(
                HttpRequest.newBuilder().uri(URI.create(url)).GET().build(),
                HttpResponse.BodyHandlers.ofString()
        ).thenAccept(resp -> {
            JsonObject json = gson.fromJson(resp.body(), JsonObject.class);

            if (json.get("status").getAsInt() == 1) {
                result.complete(json.get("request").getAsString());
            } else if ("CAPCHA_NOT_READY".equals(
                    json.get("request").getAsString())) {
                // Schedule next poll
                scheduler.schedule(
                        () -> doPoll(captchaId, result, attempt + 1),
                        5, TimeUnit.SECONDS
                );
            } else {
                result.completeExceptionally(new RuntimeException(
                        json.get("request").getAsString()));
            }
        }).exceptionally(ex -> {
            result.completeExceptionally(ex);
            return null;
        });
    }

    private String buildFormData(Map<String, String> params) {
        return params.entrySet().stream()
                .map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8)
                        + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                .collect(Collectors.joining("&"));
    }

    public void shutdown() {
        scheduler.shutdown();
    }
}

Batch Solving with allOf

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class BatchSolver {

    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("CAPTCHAAI_API_KEY");
        CaptchaAiClient client = new CaptchaAiClient(apiKey);

        // Create tasks
        List<CaptchaTask> tasks = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            tasks.add(new CaptchaTask(
                    "task_" + i,
                    "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
                    "https://example.com/page/" + i
            ));
        }

        System.out.printf("Solving %d CAPTCHAs...%n", tasks.size());
        long start = System.currentTimeMillis();

        // Launch all tasks concurrently
        List<CompletableFuture<TaskResult>> futures = new ArrayList<>();
        for (CaptchaTask task : tasks) {
            CompletableFuture<TaskResult> future = client
                    .solveCaptcha(task.sitekey, task.pageurl)
                    .thenApply(solution -> new TaskResult(
                            task.taskId, solution, null))
                    .exceptionally(ex -> new TaskResult(
                            task.taskId, null, ex.getMessage()));
            futures.add(future);
        }

        // Wait for all
        CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
        ).join();

        // Collect results
        long elapsed = System.currentTimeMillis() - start;
        int solved = 0, failed = 0;

        for (CompletableFuture<TaskResult> f : futures) {
            TaskResult result = f.get();
            if (result.solution != null) {
                solved++;
                System.out.printf("  ✓ %s: %s...%n",
                        result.taskId,
                        result.solution.substring(0,
                                Math.min(30, result.solution.length())));
            } else {
                failed++;
                System.out.printf("  ✗ %s: %s%n",
                        result.taskId, result.error);
            }
        }

        System.out.printf("%nDone in %.1fs — %d solved, %d failed%n",
                elapsed / 1000.0, solved, failed);
        client.shutdown();
    }
}

record CaptchaTask(String taskId, String sitekey, String pageurl) {}

record TaskResult(String taskId, String solution, String error) {}

Concurrency Control with Semaphore

import java.util.concurrent.Semaphore;

public class ThrottledBatchSolver {

    private final CaptchaAiClient client;
    private final Semaphore semaphore;

    public ThrottledBatchSolver(String apiKey, int maxConcurrency) {
        this.client = new CaptchaAiClient(apiKey);
        this.semaphore = new Semaphore(maxConcurrency);
    }

    public CompletableFuture<TaskResult> solveThrottled(CaptchaTask task) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return task;
        }).thenCompose(t ->
                client.solveCaptcha(t.sitekey(), t.pageurl())
                        .thenApply(sol -> new TaskResult(t.taskId(), sol, null))
                        .exceptionally(ex -> new TaskResult(t.taskId(), null, ex.getMessage()))
                        .whenComplete((result, ex) -> semaphore.release())
        );
    }
}

Chaining Operations

// Submit → Solve → Use token → Report
CompletableFuture<Void> pipeline = client
        .solveCaptcha(sitekey, pageurl)
        .thenApply(token -> submitForm(token))       // Use the token
        .thenApply(response -> extractData(response)) // Process response
        .thenAccept(data -> saveToDatabase(data))     // Store result
        .exceptionally(ex -> {
            System.err.println("Pipeline failed: " + ex.getMessage());
            return null;
        });

Troubleshooting

Issue Cause Fix
CompletionException wrapping real error exceptionally wraps in CompletionException Call getCause() to get the original exception
Thread pool exhaustion Default ForkJoinPool too small for many tasks Use custom executor: CompletableFuture.supplyAsync(..., executor)
HttpClient connection timeout Too many concurrent requests Reduce concurrency with Semaphore; increase HttpClient pool
Memory leak from uncompleted futures Timeout not handled properly Always set a global timeout on the batch operation

FAQ

Should I use CompletableFuture or virtual threads (Java 21+)?

For Java 21+, virtual threads simplify concurrent code significantly — you can use blocking Thread.sleep and synchronous HTTP calls in virtual threads. For Java 11–17, CompletableFuture is the standard async approach.

What about Reactive Streams (Project Reactor, RxJava)?

CompletableFuture is sufficient for CAPTCHA solving. Reactive libraries add complexity that's unnecessary unless you're already in a reactive framework (Spring WebFlux).

How many concurrent CAPTCHAs can Java handle?

Java's async model is very efficient. With CompletableFuture, you can manage hundreds of concurrent solves without issues. The limit is CaptchaAI's capacity, not the JVM.

Next Steps

Build async CAPTCHA pipelines in Java — get your CaptchaAI API key and compose your solving workflow.

Related guides:

Discussions (0)

No comments yet.

Related Posts

Tutorials Solve CAPTCHAs with Java Using CaptchaAI
Java tutorial for solving re CAPTCHA, Turnstile, and image CAPTCHAs using the Captcha AI REST API with Http Client.

Java tutorial for solving re CAPTCHA, Turnstile, and image CAPTCHAs using the Captcha AI REST API with Http Cl...

Automation All CAPTCHA Types Java
Mar 05, 2026
DevOps & Scaling Ansible Playbooks for CaptchaAI Worker Deployment
Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates, and health checks across your server fleet.

Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates...

Automation Python All CAPTCHA Types
Apr 07, 2026
DevOps & Scaling Blue-Green Deployment for CAPTCHA Solving Infrastructure
Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switching, and rollback strategies with Captcha AI.

Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switchin...

Automation Python All CAPTCHA Types
Apr 07, 2026
Troubleshooting CaptchaAI API Error Handling: Complete Decision Tree
Complete decision tree for every Captcha AI API error.

Complete decision tree for every Captcha AI API error. Learn which errors are retryable, which need parameter...

Automation Python All CAPTCHA Types
Mar 17, 2026
Tutorials Using Fiddler to Inspect CaptchaAI API Traffic
How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and responses — filters, breakpoints, and replay for tr...

How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and r...

Automation Python All CAPTCHA Types
Mar 05, 2026
Tutorials CAPTCHA Handling in Mobile Apps with Appium
Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web sitekeys, solve, and inject tokens on Android and i OS.

Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web View sitekeys, solve, and i...

Automation Python All CAPTCHA Types
Feb 13, 2026
Tutorials Streaming Batch Results: Processing CAPTCHA Solutions as They Arrive
Process CAPTCHA solutions the moment they arrive instead of waiting for tasks to complete — use async generators, event emitters, and callback patterns for stre...

Process CAPTCHA solutions the moment they arrive instead of waiting for all tasks to complete — use async gene...

Automation Python All CAPTCHA Types
Apr 07, 2026
Reference CaptchaAI CLI Tool: Command-Line CAPTCHA Solving and Testing
A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parameters, and integrate with shell scripts and CI/CD p...

A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parame...

Automation Python All CAPTCHA Types
Feb 26, 2026
DevOps & Scaling Auto-Scaling CAPTCHA Solving Workers
Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates.

Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates...

Automation Python All CAPTCHA Types
Mar 23, 2026
API Tutorials How to Solve reCAPTCHA v2 Callback Using API
how to solve re CAPTCHA v 2 callback implementations using Captcha AI API.

Learn how to solve re CAPTCHA v 2 callback implementations using Captcha AI API. Detect the callback function,...

Automation reCAPTCHA v2 Webhooks
Mar 01, 2026
API Tutorials Solve GeeTest v3 CAPTCHA with Python and CaptchaAI
Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API.

Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API. Includes...

Automation Python Testing
Mar 23, 2026
API Tutorials Case-Sensitive CAPTCHA API Parameter Guide
How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI.

How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI. Covers when to use, comm...

Python Web Scraping Image OCR
Apr 09, 2026