GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Modern HTTP client | java.evolved

Home / I/O / Modern HTTP client
I/O Beginner

Modern HTTP client

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Use the built-in HttpClient for clean, modern HTTP requests.

HTTP I/O
Code Comparison
✕ 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();
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📐

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.

Old Approach
HttpURLConnection
Modern Approach
HttpClient
Since JDK
11
Difficulty
Beginner
JDK Support
Modern HTTP client
Available

Widely available since JDK 11 (Sept 2018)

How it works

HttpClient supports HTTP/1.1 and HTTP/2, async requests, WebSocket, custom executors, and connection pooling. No more casting URLConnection or manually reading InputStreams.

Related Documentation
HttpClient (JEP 321) ↗ HttpClient ↗
Proof
View proof source ↗
Related patterns
I/O Beginner

Reading files

Java 8
StringBuilder sb = new StringBuilder();
try (BufferedReader br =
    new BufferedReader(
        new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null)
        sb.append(line).append("\n");
}
String content = sb.toString();
Java 11+
String content =
    Files.readString(Path.of("data.txt"));
Hover to see modern ➜
JDK 11+ →
I/O Beginner

InputStream.transferTo()

Java 8
byte[] buf = new byte[8192];
int n;
while ((n = input.read(buf)) != -1) {
    output.write(buf, 0, n);
}
Java 9+
input.transferTo(output);
Hover to see modern ➜
JDK 9+ →
I/O Beginner

Try-with-resources improvement

Java 8
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
    use(c);
}
Java 9+
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
    use(conn);
}
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.