API Screenshot en Java : exemple de bout en bout
HttpClient Java 11, Gson pour le JSON, boucle de polling et écriture du PNG — avec fragment Maven pour classpath.
Java 11+ côté serveur
java.net.http.HttpClient gère TLS 1.2+, les timeouts et le streaming sans Apache HttpClient. Gson reste l’option la plus légère pour parser l’enveloppe { success, data }. Pour un client supporté, préférez le SDK Java. Référence des paramètres : Developers.
Classe complète (messages en français)
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 CaptureEcran {
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 cle = System.getenv("SCREENSHOTCENTER_API_KEY");
if (cle == null || cle.isBlank()) {
System.err.println("Définissez 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 = creer(client, cle, page);
System.out.println("Identifiant de capture : " + id);
attendreTermine(client, cle, id, Duration.ofSeconds(2), Duration.ofMinutes(5));
Path fichier = Path.of("screenshot.png");
telechargerVignette(client, cle, id, fichier);
System.out.println("Fichier écrit : " + fichier.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() + " : " + resp.body());
}
JsonObject racine = GSON.fromJson(resp.body(), JsonObject.class);
if (!racine.get("success").getAsBoolean()) {
throw new IOException("Erreur API : " + resp.body());
}
return racine.getAsJsonObject("data");
}
private static long creer(HttpClient c, String cle, String page) throws Exception {
String q = enc(Map.of("key", cle, "url", page, "country", "us"));
return getJson(c, BASE + "/screenshot/create?" + q).get("id").getAsLong();
}
private static JsonObject info(HttpClient c, String cle, long id) throws Exception {
return getJson(c, BASE + "/screenshot/info?" + enc(Map.of("key", cle, "id", Long.toString(id))));
}
private static void attendreTermine(HttpClient c, String cle, long id, Duration poll, Duration max)
throws Exception {
long limite = System.nanoTime() + max.toNanos();
while (System.nanoTime() < limite) {
String st = info(c, cle, id).get("status").getAsString();
if ("finished".equals(st)) {
return;
}
if ("error".equals(st)) {
throw new IOException("La capture a échoué côté API");
}
Thread.sleep(poll.toMillis());
}
throw new IOException("Délai dépassé pour la capture " + id);
}
private static void telechargerVignette(HttpClient c, String cle, long id, Path dest) throws Exception {
String q = enc(Map.of("key", cle, "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("Téléchargement 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>