Lesson 44 • Advanced
Networking & HTTP
Build networked Java applications — from low-level TCP sockets to the modern HttpClient API. Learn to make REST calls, fire async requests, use WebSockets for real-time communication, and handle network failures gracefully.
Before You Start
You should know IO & NIO (sockets use streams), CompletableFuture (async HTTP), and JSON processing (parsing API responses). Basic HTTP knowledge helps.
What You'll Learn
- ✅ TCP sockets: ServerSocket and Socket
- ✅ Java 11+ HttpClient for REST calls
- ✅ Async HTTP requests with CompletableFuture
- ✅ WebSocket client and server
- ✅ URL and URI handling
- ✅ SSL/TLS and secure connections
1️⃣ Networking Mental Model
Analogy: Think of networking like a phone system. A ServerSocket is a receptionist waiting for calls (listening on a port). A Socket is the phone line connecting two people. HttpClient is a smart phone that speaks HTTP — you just say "GET me this page" and it handles the protocol.
| Level | API | Protocol | Use Case |
|---|---|---|---|
| Low-level | Socket / ServerSocket | TCP | Custom protocols, chat |
| High-level | HttpClient | HTTP/1.1, HTTP/2 | REST APIs |
| Real-time | WebSocket | WS | Live data, notifications |
| UDP | DatagramSocket | UDP | Gaming, video streaming |
Try It: TCP Echo Server & Client
// 💡 Try modifying this code and see what happens!
// TCP Socket communication — server and client
console.log("=== TCP Echo Server & Client ===\n");
// Simulated TCP communication
class ServerSocket {
constructor(port) { this.port = port; this.queue = []; }
accept() { return this.queue.shift() || null; }
}
class Socket {
constructor() { this.buffer = []; this.connected = false; }
connect(host, port) { this.host = host; this.port = port; this.connected = true; }
send(msg) { this.bu
...2️⃣ HttpClient — Modern REST Calls
Java 11 introduced HttpClient — a modern, fluent API that replaces the old URLConnection. It supports HTTP/2, async requests, WebSockets, and connection pooling out of the box.
HttpClient.newHttpClient() — create client (reuse across requests)
HttpRequest.newBuilder() — build request with fluent API
client.send(req, ofString()) — synchronous call
client.sendAsync(req, ofString()) — async with CompletableFuture
Try It: HttpClient REST API Calls
// 💡 Try modifying this code and see what happens!
// Java 11 HttpClient — making REST API calls
console.log("=== HttpClient REST API ===\n");
// Simulated HTTP client
class HttpClient {
constructor() { this.requestCount = 0; }
send(method, url, body, headers = {}) {
this.requestCount++;
let start = performance.now();
// Simulated responses
let responses = {
"GET /api/users": { status: 200, body: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] },
"GE
...Common Mistakes
- ⚠️ Forgetting timeouts: Network calls without timeouts can hang forever. Always set
connectTimeoutand requesttimeout - ⚠️ Not closing sockets: Leaked sockets exhaust OS file descriptors. Use try-with-resources
- ⚠️ Blocking the main thread: Use
sendAsync()or background threads - ⚠️ Ignoring HTTP status codes: Always check
res.statusCode()before parsing - ⚠️ Using URLConnection in 2024:
HttpClient(Java 11+) is the modern replacement
Pro Tips
- 💡 Reuse HttpClient — it manages connection pools internally. Create one, share everywhere
- 💡 HTTP/2 is automatic — HttpClient negotiates HTTP/2 with supporting servers
- 💡 Download files — use
BodyHandlers.ofFile(Path)to stream directly to disk - 💡 Retry with backoff — implement retry: wait 1s, 2s, 4s between attempts
Try It: Async HTTP & Retry Logic
// 💡 Try modifying this code and see what happens!
// Async HTTP requests and retry with exponential backoff
console.log("=== Async HTTP & Retry ===\n");
// 1. Async requests — fire all at once
console.log("1. ASYNC REQUESTS (parallel):");
let apis = [
{ url: "/api/users", time: 120 },
{ url: "/api/orders", time: 85 },
{ url: "/api/products", time: 200 },
{ url: "/api/analytics", time: 150 },
];
let syncTotal = 0;
let asyncMax = 0;
apis.forEach(api => {
syncTotal += api.time;
asy
...📋 Quick Reference
| Task | API | Since |
|---|---|---|
| HTTP GET | client.send(req, ofString()) | Java 11 |
| Async HTTP | client.sendAsync(req, handler) | Java 11 |
| POST body | BodyPublishers.ofString(json) | Java 11 |
| TCP Server | new ServerSocket(port) | Java 1.0 |
| WebSocket | client.newWebSocketBuilder() | Java 11 |
| Timeout | .timeout(Duration.ofSeconds(10)) | Java 11 |
🎉 Lesson Complete!
You've mastered Java networking! You can build TCP servers, call REST APIs, fire async requests, and use WebSockets. Next: Thread Pools — managing concurrent work efficiently with ExecutorService.
Sign up for free to track which lessons you've completed and get learning reminders.