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.

    LevelAPIProtocolUse Case
    Low-levelSocket / ServerSocketTCPCustom protocols, chat
    High-levelHttpClientHTTP/1.1, HTTP/2REST APIs
    Real-timeWebSocketWSLive data, notifications
    UDPDatagramSocketUDPGaming, video streaming

    Try It: TCP Echo Server & Client

    Try it Yourself »
    JavaScript
    // 💡 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 it Yourself »
    JavaScript
    // 💡 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 connectTimeout and request timeout
    • ⚠️ 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 it Yourself »
    JavaScript
    // 💡 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

    TaskAPISince
    HTTP GETclient.send(req, ofString())Java 11
    Async HTTPclient.sendAsync(req, handler)Java 11
    POST bodyBodyPublishers.ofString(json)Java 11
    TCP Servernew ServerSocket(port)Java 1.0
    WebSocketclient.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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service