Skip to content

Java Screenshot API: End-to-End Example

Use Java 11 HttpClient plus Gson to call ScreenshotCenter: create a screenshot, poll /screenshot/info, and stream /screenshot/thumbnail to disk.

Java 11+ and HttpClient

The platform HTTP client handles TLS, timeouts, and response streaming. Add Gson for JSON. See the Java SDK for a supported client, and Developers for every query parameter.

Runnable class

import java.io.IOException;
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.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Map;
import java.util.StringJoiner;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public final class ScreenshotFetcher {
  private static final String BASE = "https://api.screenshotcenter.com/api/v1";
  private static final Gson GSON = new Gson();

  public static void main(String[] args) throws Exception {
    String key = System.getenv("SCREENSHOTCENTER_API_KEY");
    if (key == null || key.isBlank()) { System.err.println("Set SCREENSHOTCENTER_API_KEY"); System.exit(1); }
    String page = args.length > 0 ? args[0] : "https://example.com";
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
    long id = createScreenshot(client, key, page);
    System.out.println("Queued id=" + id);
    waitFinished(client, key, id, Duration.ofSeconds(2), Duration.ofMinutes(5));
    Path out = Path.of("screenshot.png");
    downloadThumbnail(client, key, id, out);
    System.out.println("Wrote " + out.toAbsolutePath());
  }

  private static String enc(Map<String, String> p) {
    StringJoiner j = new StringJoiner("&");
    for (var e : p.entrySet()) {
      j.add(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
          + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8));
    }
    return j.toString();
  }

  private static JsonObject getJson(HttpClient c, String url) throws Exception {
    var req = HttpRequest.newBuilder(URI.create(url)).GET().timeout(Duration.ofMinutes(2)).build();
    HttpResponse<String> resp = c.send(req, HttpResponse.BodyHandlers.ofString());
    if (resp.statusCode() != 200) throw new IOException("HTTP " + resp.statusCode());
    JsonObject root = GSON.fromJson(resp.body(), JsonObject.class);
    if (!root.get("success").getAsBoolean()) throw new IOException(resp.body());
    return root.getAsJsonObject("data");
  }

  private static long createScreenshot(HttpClient c, String key, String page) throws Exception {
    String q = enc(Map.of("key", key, "url", page, "country", "us"));
    return getJson(c, BASE + "/screenshot/create?" + q).get("id").getAsLong();
  }

  private static JsonObject info(HttpClient c, String key, long id) throws Exception {
    return getJson(c, BASE + "/screenshot/info?" + enc(Map.of("key", key, "id", Long.toString(id))));
  }

  private static void waitFinished(HttpClient c, String key, long id, Duration poll, Duration max) throws Exception {
    long until = System.nanoTime() + max.toNanos();
    while (System.nanoTime() < until) {
      String st = info(c, key, id).get("status").getAsString();
      if ("finished".equals(st)) return;
      if ("error".equals(st)) throw new IOException("screenshot error");
      Thread.sleep(poll.toMillis());
    }
    throw new IOException("timeout");
  }

  private static void downloadThumbnail(HttpClient c, String key, long id, Path dest) throws Exception {
    String q = enc(Map.of("key", key, "id", Long.toString(id)));
    var req = HttpRequest.newBuilder(URI.create(BASE + "/screenshot/thumbnail?" + q)).GET().timeout(Duration.ofMinutes(2)).build();
    HttpResponse<byte[]> resp = c.send(req, HttpResponse.BodyHandlers.ofByteArray());
    if (resp.statusCode() != 200) throw new IOException("HTTP " + resp.statusCode());
    Files.write(dest, resp.body());
  }
}

Maven

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.11.0</version>
</dependency>