Java Examples
Solve text/image captchas from Java 11+ using the built-in java.net.http.HttpClient — no external dependencies.
Synchronous OCR with HttpClient
POST the image as multipart form data (field name captcha) to /api/process.php with your API key in the Authorization header. The prediction comes back in the same response.
java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
public class CaptchaKingsOcr {
private static final String API_KEY = "YOUR_API_KEY";
private static final String ENDPOINT = "https://captchakings.com/api/process.php";
public static void main(String[] args) throws IOException, InterruptedException {
Path image = Path.of("captcha.png");
String boundary = "----CKBoundary" + System.currentTimeMillis();
// Build multipart body manually (no external libs needed)
ByteArrayOutputStream body = new ByteArrayOutputStream();
byte[] fileBytes = Files.readAllBytes(image);
String head = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"captcha\"; filename=\"captcha.png\"\r\n"
+ "Content-Type: image/png\r\n\r\n";
body.write(head.getBytes(StandardCharsets.UTF_8));
body.write(fileBytes);
body.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(ENDPOINT))
.timeout(Duration.ofSeconds(10)) // OCR p95 is 2.5s; 10s is safe
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// With a JSON lib (Jackson/Gson) parse properly; quick extraction:
String json = response.body();
String prediction = json.replaceAll(".*\"prediction\"\\s*:\\s*\"([^\"]+)\".*", "$1");
System.out.println("Solved: " + prediction);
} else {
// 4xx errors are never billed
System.err.println("HTTP " + response.statusCode() + ": " + response.body());
}
}
}
Notes
- Timeouts: 10s is safe for OCR (measured p95: 2.5s). Use 30s for
/api/amazon.php. - File constraints: JPG, PNG, or GIF, max 5 MB. See API Endpoints for the full schema.
- Billing: $0.80 per 1,000 OCR solves; only successful solves are charged.
- JSON parsing: use Jackson or Gson in production instead of the regex shortcut above.