lkrequest-java
A Java HTTP client with byte-level TLS, HTTP/2 and HTTP/3 fingerprint control, powered by Rust.
Browser presets · Proxies and pools · HTTP/3 · Sync and async · Java FFM, no JNI
Installation ·
Quick start ·
Usage ·
Examples ·
Changelog ·
简体中文
Java bindings for lkrequest — a Rust HTTP client with byte-level TLS / HTTP2 / HTTP3(QUIC) fingerprint control — built on Java Panama / FFM (java.lang.foreign, JEP 454).
For browser fingerprint emulation, anti-detection research, and web scraping — letting Java precisely replicate a real browser’s TLS ClientHello, HTTP/2 SETTINGS, QUIC transport parameters, and header order.
⚠️ Requirements
| Item |
Requirement |
| Minimum JDK |
Java 22. The library is compiled with release 22, and FFM was finalized in JDK 22 (JEP 454) — it will not run below 22. |
| Recommended |
JDK 25 (used for development and testing; runs on 22/23/24/25+) |
| Launch flag |
Must add --enable-native-access=ALL-UNNAMED (see Good to know) |
| Build tool |
Maven |
Features
- Browser fingerprint presets — Chrome / Firefox / Safari TLS + HTTP/2 fingerprints, selected by name (
Client.create("chrome_150")); Client.createDefault() uses chrome_155; LkPreset.names() lists what the loaded library supports
- Fingerprint randomization — per-connection TLS extension-order jitter (drifts JA3, still a real browser); cross-layer synthetic fingerprints require a library built with the
synthetic-fp feature
- Custom profiles —
LkPreset.exportJson() writes a preset as a complete profile bundle that presetJson() / presetFile() load back, edited or not (LkException.presetError() says why a bundle was rejected); tlsProfileJson() / h2ProfileJson() / quicTlsProfileJson() replace a single layer
- Sync + async — every request has
send() and sendAsync() (CompletableFuture, backed by a virtual thread blocking on completion; cancel(true) truly aborts an in-flight request)
- Streaming responses —
sendStreaming() / readAsync() read large responses chunk by chunk; abort() interrupts
- HTTP/2 and HTTP/3(QUIC) — Alt-Svc auto-upgrade,
http3Only() / http3WithFallback(), H3 header ordering (QUIC requires a library built with the quic-h3 feature)
- Connection pools —
SessionPool / ProxyPool: proxy rotation (round-robin / random), health checks, bad-proxy circuit breaking, dynamic ProxyProvider
- Cookie management — three levels (Session / Request / Response), with attribute setting, attribute reading (
CookieInfo: domain, path, Secure, HttpOnly, SameSite, expiry) and per-request override
- Multipart upload — text + file parts
- Retry strategies — fixed interval / exponential backoff (with optional jitter)
- Timeouts and resends — per-phase and total deadlines plus a response read-idle timeout, each of which can be turned off (
disableTimeoutTotal() for long-lived streams); resending after a closed connection (retryOnConnectionClose) and HTTP/2-to-HTTP/1.1 fallback (fallbackH2ToH1) are opt-in
- Attempt limits and summaries — cap the connections a request may start (
connectAttemptLimit) and how often it may be resent (extraHttpAttemptLimit) at Client / Session / Request level; attemptSummary() reports what a request did
- Proxy — HTTP CONNECT / SOCKS5 (with auth), configurable at Client / Session / Request levels;
ProxyConfig carries credentials a URL cannot (static HTTP auth schemes such as Preshared / PrivateToken, sent in Proxy-Authorization or Authorization)
- MASQUE proxies (experimental) —
masque:// (RFC 9298 CONNECT-UDP) tunnels QUIC/HTTP3 through an HTTP/3 proxy, configured with MasqueConfig; requires a library built with the masque feature
- Custom DNS — preset resolvers (System / Google / Cloudflare / Quad9), or a custom
DnsResolver callback; the DNS-over-HTTPS presets require a library built with the doh feature
- SOCKS5 UDP probing —
socks5UdpProbe() detects UDP ASSOCIATE support (for QUIC-over-SOCKS5)
- Automatic decompression — gzip / br / deflate / zstd, controllable via
AcceptEncoding
- Certificate management — custom CA, verification toggle, system certs, ECH, TLS keylog, TLS session cache (
tlsSessionCache / tlsSessionCacheTtl); Trust Anchor Identifiers negotiation (trustAnchorPolicy / addTrustAnchorBinding), reported per TLS connection by diagnostics().trustAnchor()
- Header / cookie ordering — configurable at Client / Session / Request levels;
h2PriorityWeight() overrides one request’s HTTP/2 HEADERS priority weight; http1TitleCaseHeaders(false) sends HTTP/1.1 header names in lowercase instead of Title-Case
- Connection prewarming —
preconnect() / preconnectAsync() establish connections ahead of time to cut first-request latency
- Request diagnostics —
diagnostics() returns per-request phase timings (DNS / TCP / TLS / QUIC / TTFB / total) and connection details as a RequestDiagnostics
- Runtime metrics —
LkMetrics.snapshot() pulls process-level byte / connection / request counters (real counts require a library built with the telemetry feature)
- Typed errors —
LkException carries error code, phase, retryable flag, HTTP status, and diagnostics
- Self-managing handles — every native handle implements
AutoCloseable (explicit release via try-with-resources) + a Cleaner fallback (GC reclaims if you forget to close); close() is idempotent
Installation
Maven:
<dependency>
<groupId>com.ezxlabs</groupId>
<artifactId>lkrequest</artifactId>
<version>0.1.0</version>
</dependency>
Gradle (Kotlin DSL):
implementation("com.ezxlabs:lkrequest:0.1.0")
Quick Start
Minimal GET — all handles closed explicitly with try-with-resources:
import com.ezxlabs.lkrequest.Client;
import com.ezxlabs.lkrequest.Session;
import com.ezxlabs.lkrequest.Response;
try (Client client = Client.createDefault();
Session session = client.newSession();
Response resp = session.get("https://example.com/").send()) {
System.out.println(resp.status()); // 200
System.out.println(resp.negotiatedVersion()); // HTTP_2
System.out.println(resp.text());
}
POST JSON with a fingerprint preset:
try (Client client = Client.create("chrome_150");
Session session = client.newSession();
Response resp = session.post("https://httpbin.org/post")
.header("x-demo", "lkrequest")
.query("from", "readme")
.json("{\"name\":\"Zero\",\"lang\":\"java\"}")
.send()) {
resp.errorForStatus(); // throws LkException on 4xx/5xx, otherwise returns self
System.out.println(resp.text());
}
Usage
Building and sending requests
try (Response resp = session.post("https://httpbin.org/post")
.header("accept", "application/json")
.query("page", "1")
.bearerAuth("my-token") // or .basicAuth(user, pass)
.json("{\"hello\":\"world\"}") // or .text(...) / .body(bytes) / .form(map)
.timeout(Duration.ofSeconds(10))
.send()) {
System.out.println(resp.status() + " " + resp.firstHeader("content-type").orElse(""));
}
Custom Client
ClientBuilder is a chained builder:
try (Client client = Client.builder()
.preset("chrome_150")
.verify(true)
.useNativeCerts(true)
.addDefaultHeader("accept-language", "en-US,en;q=0.9")
.timeoutTotal(Duration.ofSeconds(30))
.maxConnectionsPerSession(16)
.fallbackH2ToH1(true)
.build()) {
// ...
}
Session configuration and retry
try (Session session = new SessionBuilder(client)
.proxy("socks5://user:pass@host:1080")
.maxRedirects(5)
.http2Only() // or http3WithFallback() / http3Only() ...
.defaultAcceptEncoding(AcceptEncoding.GZIP, AcceptEncoding.BR)
.retryExponential(3, Duration.ofMillis(50), Duration.ofMillis(500), true)
.build()) { // or retryFixed(2, Duration.ofMillis(100))
// ...
}
Attempt limits and summaries
Resending a request whose pooled connection closed is off by default. Once allowed, attempt limits cap it per request; sessions and requests inherit a limit and may only tighten it.
try (Client client = Client.builder()
.retryOnConnectionClose(true) // allow resending after a pooled connection closed
.extraHttpAttemptLimit(2) // ...at most twice per request
.connectAttemptLimit(3) // at most three new TCP/QUIC connections per request
.build();
Session session = client.newSession();
Response resp = session.get(url).attemptSummary(true).send()) {
AttemptSummary summary = resp.attemptSummary().orElseThrow();
System.out.println(summary.httpSubmissions() + " sent, " + summary.connectInitiations() + " connections");
}
A failed request carries its summary in LkException.attemptSummary(), whose denialReason() says why it was not resent.
Cookies
session.setCookie("https://example.com", "token", "abc123");
Optional<String> token = session.getCookie("https://example.com", "token");
// with attributes: domain / path / Secure / HttpOnly / SameSite / expiry
List<CookieInfo> sent = session.getCookiesWithAttrs("https://example.com/"); // cookies sent to this URL
List<CookieInfo> all = session.getAllCookies(); // the whole jar, all domains
for (CookieInfo c : all) {
System.out.println(c.name() + " @ " + c.domain().orElse("-") + c.path()
+ c.expires().map(e -> ", expires " + e).orElse(", session cookie"));
}
// per-request override of the jar value
session.get(url).cookieOverride("token", "fresh-value").send();
Multipart upload
MultipartBody mp = MultipartBody.builder()
.text("title", "report")
.file("document", "report.pdf", "application/pdf", pdfBytes)
.build();
try (Response resp = session.post("https://example.com/upload").multipart(mp).send()) {
// ...
}
Streaming responses
StreamingResponse reads chunk by chunk; read() returns null on natural EOF, while calling read() after abort()/close() throws STREAM_CLOSED (not EOF).
try (StreamingResponse stream = session.get("https://example.com/large-file").sendStreaming()) {
byte[] chunk;
while ((chunk = stream.read()) != null) {
process(chunk);
}
}
The total timeout (120 seconds by default) covers reading the body as well. For long downloads or server-sent events, turn it off and limit the wait for each chunk instead:
client = Client.builder().disableTimeoutTotal().timeoutReadIdle(Duration.ofSeconds(30)).build();
Async and cancellation
sendAsync() returns a CompletableFuture immediately, backed by a virtual thread blocking on completion; cancel(true) propagates to native and truly aborts the request.
List<CompletableFuture<String>> futures = urls.stream()
.map(url -> session.get(url).sendAsync()
.handle((resp, ex) -> {
if (ex != null) return url + " → failed";
try (resp) { return url + " → " + resp.status(); }
}))
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
Also available: sendStreamingAsync(), preconnectAsync(), SessionPool/ProxyPool.acquireAsync(), readAsync().
Proxy
// Single proxy: Session level or request level
session = new SessionBuilder(client).proxy("http://user:pass@proxy:8080").build();
session.get(url).proxy("socks5://other:1080").send(); // per-request override
// Proxy pool: rotate URLs, mark bad proxies
try (ProxyPool pool = new ProxyPoolBuilder()
.addProxies(List.of("socks5://p1:1080", "http://p2:8080"))
.rotation(RotationStrategy.ROUND_ROBIN)
.build();
ProxyGuard guard = pool.acquire()) {
String proxyUrl = guard.url();
}
// Session pool: each session bound to a different proxy
try (SessionPool sp = new SessionPoolBuilder(client)
.addProxy("http://p1:8080")
.maxSessions(8)
.build();
SessionPoolGuard g = sp.acquire();
Response resp = g.requestNew("GET", "https://example.com").send()) {
// closing the guard returns the session to the pool; after sp.markBad(g) it is discarded instead
}
Dynamic proxy source: implement the ProxyProvider interface and pass it to ProxyPoolBuilder.provider(...) or SessionPoolBuilder.provider(...).
Credentials a URL cannot carry go through ProxyConfig. Builders copy it, so close it yourself:
try (ProxyConfig proxy = ProxyConfig.parse("http://proxy.example:8080")
.httpAuth("Preshared", "my-psk") // or .userPass(user, pass)
.authHeader(ProxyAuthHeader.PROXY_AUTHORIZATION); // or AUTHORIZATION
Session session = new SessionBuilder(client).proxy(proxy).build()) {
// also accepted by ProxyPoolBuilder.addProxy(proxy)
}
// ProxyPool.markBad takes the proxy's identity, not its URL; each call counts one failure
// toward the badProxyConfig(...) threshold (3 by default)
try (ProxyConfig p2 = ProxyConfig.parse("http://p2:8080")) {
pool.markBad(p2.identity());
}
QUIC / HTTP3
QUIC/H3 requires a native library built with the quic-h3 feature; probe with featureSupported first:
if (LkRequest.featureSupported("quic-h3")) {
try (Session session = new SessionBuilder(client)
.http3WithFallback() // prefer H3, fall back to H2
.build()) {
// ...
}
}
MASQUE proxies (experimental)
A masque:// proxy (RFC 9298 CONNECT-UDP) carries QUIC/HTTP3 to the target over an outer HTTP/3 connection. It needs a native library built with the masque feature. The bundled libraries are not, so new MasqueConfig() throws there — constructing it is the probe, since featureSupported has no masque entry. HTTP/1.1 and HTTP/2 requests through such a proxy fail with a proxy error rather than connecting directly.
try (MasqueConfig masque = new MasqueConfig()
.addCaCertsPem(privateCaPem) // trust anchors for the hop to the proxy only
.useNativeCerts(false);
ProxyConfig proxy = ProxyConfig.parse("masque://proxy.example");
Client client = Client.builder().masque(masque).build();
Session session = new SessionBuilder(client).proxy(proxy).http3Only().build()) {
// ...
}
Health checks skip MASQUE proxies unless the pool also gets masqueTunnelProbe(masque), which requires healthCheck(...).
Custom DNS
// preset resolver
client = Client.builder().dns(DnsConfig.CLOUDFLARE).build();
// or specific addresses: .dnsCustom("1.1.1.1:53")
// or a custom callback: .dnsResolver(myResolver) // implement the DnsResolver interface
⚠️ DnsConfig.GOOGLE_HTTPS / CLOUDFLARE_HTTPS / QUAD9_HTTPS (DNS over HTTPS) require a native library built with the doh feature. The bundled libraries are not, and the native side cannot report it: these values silently resolve through a different resolver. Use dnsCustom(...) or a DnsResolver instead.
Fingerprint randomization
// EXTENSION_ORDER is always available: jitters extension order per connection, drifts JA3 but stays a real browser
client = Client.builder()
.preset("chrome_150")
.randomize(RandomizeMode.EXTENSION_ORDER, /* layers bitmask */ -1)
.build();
RandomizeMode.RECOMBINE / FULL synthesize non-browser fingerprints (for blocklist / negative-model targets) and require a library built with the synthetic-fp feature, otherwise build() errors.
Custom profiles
String bundle = LkPreset.exportJson("chrome_158"); // every layer of the preset, as one JSON document
// ... edit it, or keep it in a file ...
try (Client custom = Client.builder().presetJson(bundle).build()) { // or presetFile(path)
// ...
} catch (LkException e) {
e.presetError().ifPresent(err -> System.out.println(err.code() + " at " + err.path()));
}
tlsProfileJson(), h2ProfileJson() and quicTlsProfileJson() replace a single layer with a profile in the form fingerprintInfoJson() reports. Edited fields do not by themselves make the traffic match a real browser.
Certificate management
client = Client.builder()
.addCaCertFile("/path/to/ca.pem") // or addCaCertPem(pemBytes)
.useNativeCerts(true) // use system certificates
.verify(false) // disable verification (dev only)
.echConfig(echBytes) // ECH
.keylogFile("/tmp/keylog.txt") // TLS keylog
.tlsSessionCacheTtl(Duration.ofMinutes(10)) // resume sessions for 10 minutes; tlsSessionCache(false) disables
.build();
// Trust Anchor Identifiers (TLS 1.3): keep the preset's IDs, allow one recovery connection (needs verification)
client = Client.builder()
.trustAnchorPolicy(TrustAnchorAdvertisement.PROFILE, TrustAnchorRecovery.ONCE)
.build();
Logging
Pick one of two modes. The native side installs a single global subscriber, so this is globally
one-shot per process: whichever call wins takes effect, and any later call — in either mode —
throws IllegalStateException.
// Forward to a Java callback
LkLog.initCallback(LogLevel.INFO, (level, target, msg) ->
System.out.printf("[%s] %s: %s%n", level, target, msg));
// Or let the native side write straight to a file (created if absent, appended otherwise;
// the parent directory must already exist)
LkLog.initFile(LogLevel.INFO, "/tmp/lkrequest.log");
Diagnostics and metrics
try (Response resp = session.get("https://example.com").send()) {
RequestDiagnostics diag = resp.diagnostics(); // empty Optionals for phases that did not run
System.out.println(diag.tls().map(Duration::toMillis).orElse(0L) + " ms TLS, " + diag.protocol().orElse("?"));
}
// process-level runtime counters (real values require a library built with the telemetry feature, else always 0)
LkMetrics.Snapshot snap = LkMetrics.snapshot();
Error handling
try (Response resp = session.get(url).send()) {
resp.errorForStatus(); // throws LkException on 4xx/5xx
} catch (LkException e) {
System.out.println(e.errorCode()); // LkErrorCode
System.out.println(e.phase()); // LkPhase
System.out.println(e.isRetryable());
}
How it works
your code
│ Client · Session · Request · Response · pools an idiomatic Java API
▼
lkrequest-java (this library)
│ Java FFM downcalls and upcalls (JEP 454)
▼
lkrequest-ffi (bundled native library)
│ a stable C ABI
▼
lkrequest-rs TLS · HTTP/2 · HTTP/3 and QUIC
proxies · DNS · cookies
Requests run on the native library’s async runtime: send() blocks the calling thread until the response is ready, and sendAsync() returns a CompletableFuture at once. What goes on the wire comes from the Rust library, so a new browser preset lands there first and reaches this library with the next native library update.
Good to know
- A preset sets fingerprints, not header values. Set
User-Agent, Accept-Language and the other headers the browser would send yourself, and keep them consistent with the preset.
- Only the Chrome presets speak HTTP/3. Firefox and Safari presets carry no QUIC parameters and stay on TCP.
- Requests are not resent or downgraded unless you allow it. A request whose pooled connection closes before the answer fails, unless
retryOnConnectionClose(true); HTTP/2 falls back to HTTP/1.1 only with fallbackH2ToH1(true).
- The total timeout covers the body. It is 120 seconds by default and includes reading a streaming body; turn it off with
disableTimeoutTotal() for long-lived streams.
- Native access must be enabled. Run with
--enable-native-access=ALL-UNNAMED; JDK 24 and later warn without it. On the module path, name the module instead: --enable-native-access=com.ezxlabs.lkrequest.
- Your Jackson version is used. The library reads native JSON with
jackson-databind but exposes no Jackson type, so whichever 2.x version your build resolves is used; 2.10 through 2.21 are tested.
- Callbacks run on native threads. A
DnsResolver, ProxyProvider or log handler runs on the native runtime while a request waits: return quickly, do not block, and do not throw.
- The bundled libraries are built with
quic-h3 and synthetic-fp. MASQUE proxies, the DNS-over-HTTPS presets and real runtime metrics need a library built with masque, doh or telemetry; point lkrequest.library.path at one.
Build and test
mvn compile # compile (also copies resources/native into target/classes)
mvn test # run tests inside the module (surefire already enables native access)
mvn install # install to the local repository for other projects to depend on
Two test switches (in pom.xml <properties>, overridable with -D):
| Property |
Meaning |
Default |
lkrequest.library.path |
Absolute path to the native library; if empty, the library bundled on the classpath is used. Native-dependent tests are skipped by Assumptions only if no library can be loaded (pure-logic tests still run) |
empty |
lkrequest.it.network |
whether to enable networked integration tests |
see pom |
Tests come in three tiers: pure logic (always runs), native without network (skips rather than fails if the library can’t load), and networked (additionally requires lkrequest.it.network=true).
Contributions
External code contributions and pull requests are not currently accepted.
Security
Report vulnerabilities privately, as SECURITY.md describes. The same file states what the project is intended for.
License
Apache-2.0. See LICENSE and NOTICE.
评论