Java · Code recipe
Run a Lighthouse audit in Java
Score any page for performance, accessibility, best practices and SEO, in Java 17+ with java.net.http.HttpClient. Every program on this page runs as it stands — each one was run against a stub of the API before it was published.
By Roger Campos · Last updated: September 2026
TL;DR
To run a Lighthouse audit in Java, POST a URL and a device to https://urlpipe.dev/lighthouse and read the JSON with Gson's JsonParser: four category scores from 0 to 1 and the lab metrics, LCP, CLS and TBT among them. An audit takes around 15 seconds, so the async variant with a webhook suits production. It costs 2 credits.
Free plan, no credit card. 1,000 credits a month.
One POST to /lighthouse runs a real Lighthouse audit in Chrome and answers with the four category scores — performance, accessibility, best practices, SEO — and the lab metrics behind the performance score. device picks mobile (the default, throttled CPU and network) or desktop.
In Java the report is read with Gson's JsonParser. Scores run from 0 to 1, so the program multiplies by 100 to print what the Lighthouse report shows; metrics carry a ready-formatted displayValue. The guide to reading a Lighthouse audit explains what each number means.
Setup
Before you start
Java 17 or later: java.net.http is in the JDK. Every program on this page reads JSON, and the JDK has no parser, so those use Gson — one jar, no dependencies of its own. In a Maven or Gradle build add com.google.code.gson:gson:2.13.1; to try a file on its own, download the jar next to it.
java -version # 17 or later
curl -sSLO https://repo1.maven.org/maven2/com/google/code/gson/gson/2.13.1/gson-2.13.1.jar
export URLPIPE_API_KEY="your_api_key"
The request
Print the four scores, LCP, CLS and TBT
"sync": true keeps the request open until the result is ready. BodyHandlers.ofString() reads the whole body as text, decoded with the charset the response names. HttpClient does not throw on a 4xx or 5xx, so check statusCode(). Gson's JsonParser reads the report; dig returns null for a category or metric Lighthouse could not compute.
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
public class LighthouseAudit {
public static void main(String[] args) throws Exception {
var request = HttpRequest.newBuilder(URI.create("https://urlpipe.dev/lighthouse"))
.header("Authorization", "Bearer " + System.getenv("URLPIPE_API_KEY"))
.header("Content-Type", "application/json")
// A sync call can take up to 60 s; HttpClient would otherwise wait forever.
.timeout(Duration.ofSeconds(90))
.POST(HttpRequest.BodyPublishers.ofString("""
{"url": "https://example.com", "device": "mobile", "sync": true}
"""))
.build();
var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
System.err.println("URLpipe answered " + response.statusCode() + ": " + response.body());
System.exit(1);
}
String body = response.body();
JsonElement report = JsonParser.parseString(body);
for (String name : List.of("performance", "accessibility", "best-practices", "seo")) {
JsonElement score = dig(report, "categories", name, "score");
System.out.println(name + ": " + (score == null ? "n/a" : Math.round(score.getAsDouble() * 100)));
}
String[][] metrics = {
{"LCP", "largest-contentful-paint"},
{"CLS", "cumulative-layout-shift"},
{"TBT", "total-blocking-time"},
};
for (String[] metric : metrics) {
JsonElement value = dig(report, "metrics", metric[1], "displayValue");
System.out.println(metric[0] + ": " + (value == null ? "n/a" : value.getAsString()));
}
}
// The value at a path of keys, or null where any step is missing or JSON null.
static JsonElement dig(JsonElement element, String... keys) {
for (String key : keys) {
if (element == null || !element.isJsonObject()) {
return null;
}
element = element.getAsJsonObject().get(key);
}
return element == null || element.isJsonNull() ? null : element;
}
}
Run it: java -cp gson-2.13.1.jar LighthouseAudit.java
Given the example response on the docs page, it prints:
performance: 95
accessibility: 88
best-practices: 92
seo: 90
LCP: 2.5 s
CLS: 0.05
TBT: 150 msAsync
The async variant: a token, a webhook and a poll
Leave out sync and the answer is a token, straight away. One HttpClient is shared by every call — it holds the connection pool, so build it once — and a switch expression covers the answers GET /result/:token can give.
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
public class LighthouseAuditAsync {
static final String API = "https://urlpipe.dev";
static final HttpClient CLIENT = HttpClient.newHttpClient();
static HttpResponse<String> send(HttpRequest.Builder builder) throws Exception {
var request = builder
.header("Authorization", "Bearer " + System.getenv("URLPIPE_API_KEY"))
.timeout(Duration.ofSeconds(30))
.build();
return CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
}
static void fail(String message) {
System.err.println(message);
System.exit(1);
}
public static void main(String[] args) throws Exception {
// No "sync": the request is accepted at once and the work carries on without you.
var accepted = send(HttpRequest.newBuilder(URI.create(API + "/lighthouse"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{
"url": "https://example.com",
"device": "mobile",
"report_to": "https://your-app.com/webhooks/urlpipe",
"labels": {"customer": "acme"}
}
""")));
if (accepted.statusCode() != 200) {
fail("URLpipe answered " + accepted.statusCode() + ": " + accepted.body());
}
String token = JsonParser.parseString(accepted.body()).getAsJsonObject().get("token").getAsString();
System.out.println("Accepted " + token);
// The result is POSTed to report_to when it is ready. Polling by token is the
// other way to collect it: no endpoint needed, and a backup for the webhook.
HttpResponse<String> response = null;
for (int attempt = 0; attempt < 60; attempt++) {
response = send(HttpRequest.newBuilder(URI.create(API + "/result/" + token)).GET());
if (response.statusCode() != 202) { // 202 means still processing
break;
}
Thread.sleep(2000);
}
switch (response.statusCode()) {
case 200 -> { }
case 202 -> fail("Still processing after two minutes; try the token again later.");
case 422 -> fail("The analysis failed: "
+ JsonParser.parseString(response.body()).getAsJsonObject().get("error").getAsString());
case 410 -> fail("The result is past the 30-day window; send the request again.");
default -> fail("URLpipe answered " + response.statusCode() + ": " + response.body());
}
String body = response.body();
JsonElement report = JsonParser.parseString(body);
for (String name : List.of("performance", "accessibility", "best-practices", "seo")) {
JsonElement score = dig(report, "categories", name, "score");
System.out.println(name + ": " + (score == null ? "n/a" : Math.round(score.getAsDouble() * 100)));
}
String[][] metrics = {
{"LCP", "largest-contentful-paint"},
{"CLS", "cumulative-layout-shift"},
{"TBT", "total-blocking-time"},
};
for (String[] metric : metrics) {
JsonElement value = dig(report, "metrics", metric[1], "displayValue");
System.out.println(metric[0] + ": " + (value == null ? "n/a" : value.getAsString()));
}
}
// The value at a path of keys, or null where any step is missing or JSON null.
static JsonElement dig(JsonElement element, String... keys) {
for (String key : keys) {
if (element == null || !element.isJsonObject()) {
return null;
}
element = element.getAsJsonObject().get(key);
}
return element == null || element.isJsonNull() ? null : element;
}
}
Run it: java -cp gson-2.13.1.jar LighthouseAuditAsync.java
Errors
Handle errors and retries
A checked URLpipeException makes the caller decide what a refusal means. firstValueAsLong reads Retry-After without a parse of your own, and a body that is not JSON (a 401 answers in plain text) falls back to an empty object.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
public class LighthouseAuditErrors {
static class URLpipeException extends Exception {
URLpipeException(String message) {
super(message);
}
}
static final HttpClient CLIENT = HttpClient.newHttpClient();
// POST a sync request and return the result body; retry the two 429s that clear by themselves.
static String urlpipe(String path, String payload) throws Exception {
final int attempts = 5;
for (int attempt = 0; attempt < attempts; attempt++) {
var request = HttpRequest.newBuilder(URI.create("https://urlpipe.dev" + path))
.header("Authorization", "Bearer " + System.getenv("URLPIPE_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(90))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
var response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status == 200) {
return response.body();
}
if (status == 401) {
throw new URLpipeException("401: the API key is missing or wrong. Check URLPIPE_API_KEY.");
}
JsonObject error;
try {
error = JsonParser.parseString(response.body()).getAsJsonObject();
} catch (RuntimeException notJson) {
error = new JsonObject();
}
String code = error.has("error") ? error.get("error").getAsString() : "";
String detail = error.has("message") ? code + ": " + error.get("message").getAsString() : code;
if (status == 429 && code.equals("rate_limited")) {
// Sending too fast: Retry-After says how long the window has left.
Thread.sleep(response.headers().firstValueAsLong("Retry-After").orElse(1) * 1000);
} else if (status == 429 && code.equals("concurrency_limit")) {
// Every parallel slot on your plan is busy with your own requests.
Thread.sleep((1L << attempt) * 1000);
} else if (status == 504) {
// Still running on our side; the token collects it from GET /result/:token.
throw new URLpipeException(
"504 processing_timeout: collect it later with token " + error.get("token").getAsString());
} else {
// 403 email_unverified, 422 (a bad parameter, or a page that would not load),
// 429 quota_exceeded: sending the same request again gets the same answer.
throw new URLpipeException(status + ": " + detail);
}
}
throw new URLpipeException("429: still refused after " + attempts + " attempts");
}
public static void main(String[] args) throws Exception {
String body;
try {
body = urlpipe("/lighthouse", """
{"url": "https://example.com", "device": "mobile", "sync": true}
""");
} catch (URLpipeException e) {
System.err.println("URLpipe: " + e.getMessage());
System.exit(1);
return;
}
JsonElement report = JsonParser.parseString(body);
for (String name : List.of("performance", "accessibility", "best-practices", "seo")) {
JsonElement score = dig(report, "categories", name, "score");
System.out.println(name + ": " + (score == null ? "n/a" : Math.round(score.getAsDouble() * 100)));
}
String[][] metrics = {
{"LCP", "largest-contentful-paint"},
{"CLS", "cumulative-layout-shift"},
{"TBT", "total-blocking-time"},
};
for (String[] metric : metrics) {
JsonElement value = dig(report, "metrics", metric[1], "displayValue");
System.out.println(metric[0] + ": " + (value == null ? "n/a" : value.getAsString()));
}
}
// The value at a path of keys, or null where any step is missing or JSON null.
static JsonElement dig(JsonElement element, String... keys) {
for (String key : keys) {
if (element == null || !element.isJsonObject()) {
return null;
}
element = element.getAsJsonObject().get(key);
}
return element == null || element.isJsonNull() ? null : element;
}
}
Run it: java -cp gson-2.13.1.jar LighthouseAuditErrors.java
Details
What to know about /lighthouse
- Lighthouse 13 reports four categories; the
pwakey is alwaysnull, kept so the shape does not change. - The performance score weights TBT 30%, LCP 25%, CLS 25%, FCP 10% and Speed Index 10%.
- INP needs real users and cannot be measured in a lab run; TBT is its lab stand-in.
"include_audits": "true"adds the full list of audits, with the elements to fix. Mobile and desktop are cached separately.- Want the audit run on a schedule, with a history and alerts? Full Stack Audit sells that as a monitored report; URLpipe is the primitive underneath.
FAQ
Frequently asked questions
Mobile or desktop — which device should I audit?
Why isn't INP in the results?
Why use the async variant for Lighthouse?
Do I need an SDK to call URLpipe from Java?
Get a key and run it.
Free plan, no card. Paste your key into URLPIPE_API_KEY and every program on this page runs as it is.