Phase 4 · Advanced JavaModule 24~38 min read

Networking

Communicate over the network with HTTP clients, sockets, and TCP/UDP.

What you'll learn

Apps rarely work alone — they fetch data from APIs, talk to servers, and stream content. This module covers networking in Java: the concepts, the modern HttpClient for calling web APIs, and raw sockets for custom protocols.

By the end you'll be able to:

  • Understand IP addresses, ports, TCP, and UDP
  • Call REST APIs with the Java HttpClient (GET and POST)
  • Handle JSON responses
  • Build TCP client/server apps with sockets
  • Know when UDP is the right tool

Networking fundamentals

Every device on a network has an IP address; each program communicates through a port number. Two protocols carry the data, and choosing between them is a fundamental trade-off of reliability versus speed:

TCP vs UDP

TCP — reliable

  • • Connection-based (handshake first)
  • • Guarantees delivery & order
  • • Web, email, file transfer, HTTP

UDP — fast

  • • Connectionless (fire and forget)
  • • No delivery/order guarantee
  • • Games, video/voice, DNS

On top of TCP sits HTTP — the protocol of the web and of REST APIs. A URL identifies a resource, and an HTTP request/response carries a method (GET, POST…), headers, a status code, and a body.

The Java HTTP Client

Since Java 11, the built-in HttpClient makes calling web APIs clean and modern (no external library needed). Build a request, send it, and read the response's status code and body:

HttpGet.java
import java.net.http.*;
import java.net.URI;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users/1"))
    .GET()
    .build();

HttpResponse<String> response =
    client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println("Status: " + response.statusCode());
System.out.println(response.body());
Example response from a REST API.

Note

client.send(...) is synchronous (it blocks). For non-blocking calls, use sendAsync(...), which returns a CompletableFuture (Module 22) — perfect for firing many requests at once.

POST & JSON

To send data, use POST (or PUT) with a body and the right Content-Type header. A text block keeps the JSON readable:

HttpPost.java
String body = """
    {"name": "Sara", "email": "sara@example.com"}
    """;

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

HttpResponse<String> res =
    client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode());   // 201 Created

Tip

The HttpClient gives you the raw JSON text. To turn it into Java objects (and back), you'll use a JSON library like Jackson or Gson — exactly what Module 25 covers next.

Sockets (TCP)

For custom protocols or direct machine-to-machine communication, drop down to sockets. A ServerSocket listens on a port and accept()s incoming connections; a client Socket connects to a host and port. Once connected, you read and write through ordinary streams:

TcpServer.java
import java.io.*;
import java.net.*;

// --- SERVER: listens on port 5000 ---
try (ServerSocket server = new ServerSocket(5000)) {
    System.out.println("Waiting for a client...");
    Socket client = server.accept();          // blocks until someone connects

    var in  = new BufferedReader(
        new InputStreamReader(client.getInputStream()));
    var out = new PrintWriter(client.getOutputStream(), true);

    out.println("Hello from the server!");
    System.out.println("Client said: " + in.readLine());
}

Note

accept() and readLine() block until data arrives. A real server handles each client on its own thread (or, ideally, a virtual thread from Module 22) so one slow client doesn't freeze the rest.

UDP

When speed matters more than guaranteed delivery — live video, online games, telemetry — UDP sends independent packets (DatagramPacket) through a DatagramSocket with no connection setup. Packets may arrive out of order or not at all, and that's an acceptable trade for the lower latency.

Recap & quick check

Key takeaways

  • Devices have IP addresses; programs use ports. TCP is reliable and ordered; UDP is fast but best-effort.
  • HTTP runs on TCP and powers REST APIs (methods, headers, status codes, bodies).
  • Use Java's built-in HttpClient (Java 11+) for GET/POST — send() blocks, sendAsync() returns a future.
  • Sockets (ServerSocket/Socket) enable custom TCP communication via streams; accept()/read() block.
  • Reach for UDP when low latency beats guaranteed delivery (games, streaming).

Quick check

1. Which protocol guarantees ordered, reliable delivery?

2. Which class calls REST APIs in modern Java?

3. What does HttpClient.send() do while waiting for a response?

4. What waits for an incoming TCP connection on the server?

5. When is UDP the better choice?

Great — your programs can now talk to the wider world. Next up: Module 25 — JSON, XML & Data Formats.