Modern HTTP client
Use the built-in HttpClient for clean, modern HTTP requests.
Porównanie kodu
✕ Java 8
URL url = new URL("https://api.com/data");
HttpURLConnection con =
(HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
// read lines, close streams...
✓ Java 11+
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.uri(URI.create("https://api.com/data"))
.build();
var response = client.send(
request, BodyHandlers.ofString());
String body = response.body();
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Builder API
Fluent builder for requests, headers, and timeouts.
HTTP/2 support
Built-in HTTP/2 with multiplexing and server push.
Async ready
sendAsync() returns CompletableFuture.
Stare podejście
HttpURLConnection
Nowoczesne podejście
HttpClient
Od JDK
11
Poziom trudności
Początkujący
Wsparcie JDK
Modern HTTP client
Dostępne
Widely available since JDK 11 (Sept 2018)
Jak to działa
HttpClient supports HTTP/1.1 and HTTP/2, async requests, WebSocket, custom executors, and connection pooling. No more casting URLConnection or manually reading InputStreams.
Powiązana dokumentacja