Networking & HTTP
Sockets basics, the modern HttpClient, and calling a real REST API.
Deutsche Übersetzung in Arbeit
Diese Lektion ist noch nicht ins Deutsche übersetzt und wird daher auf Englisch angezeigt. Der Rest der Seite ist vollständig lokalisiert.
Auf dieser Seite
Modern software rarely works alone - it talks to other computers over the
network. This lesson covers the essentials: how networking works, and how to call
a real web API using Java's modern HttpClient.
How networking works, briefly
Computers talk over networks using addresses and ports. An IP address identifies a machine; a port identifies a specific service on it (like web traffic on port 443).
An IP address is a building's street address. A port is a specific office inside it. To reach the "web service", you go to the building (IP) and knock on office 443 (HTTPS). Your message needs both to arrive at the right place.
At the lowest level, a socket is a direct connection between two machines. You rarely work with raw sockets today - higher-level tools like HTTP clients handle the details - but it's good to know they're underneath.
HTTP: the language of the web
HTTP is the protocol browsers and APIs use. The pattern is simple: a client sends a request, the server sends back a response.
Requests use methods (verbs):
| Method | Means | Example |
|---|---|---|
GET | Fetch data | Read a user's profile |
POST | Create data | Submit a new order |
PUT | Replace data | Update a whole record |
DELETE | Remove data | Delete an item |
Responses carry a status code: 200 OK, 404 Not Found, 500 Server Error.
Calling an API with HttpClient
Modern Java (11+) includes a clean, built-in HttpClient:
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(response.statusCode()); // 200
System.out.println(response.body()); // the JSON payloadThat's a complete, real HTTP call - request built, sent, response read.
Sending data with POST
String json = """
{ "name": "Ada", "role": "engineer" }
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();Asynchronous requests
HttpClient can also send requests without blocking, returning a
CompletableFuture that completes later:
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);Parsing JSON
APIs almost always speak JSON. The response body arrives as a String; to turn it into Java objects, use a library like Jackson or Gson. You'll usually map JSON straight into a record or class - clean and type-safe.
Always handle failure
Networks are unreliable: servers time out, return errors, or vanish. Always check the status code, wrap calls in error handling, and consider timeouts and retries for anything important. Never assume a request succeeded.
Quick check
Which HTTP method should you use to fetch (read) data from an API without changing anything?
Key takeaways
- Networked programs communicate via IP addresses and ports; sockets are the low-level connection.
- HTTP uses request/response with methods (GET, POST, PUT, DELETE) and status codes (200, 404, 500).
- Java's built-in HttpClient (11+) sends requests and reads responses cleanly.
- Use POST with a body and Content-Type header to send data; sendAsync for non-blocking calls.
- Parse JSON responses with Jackson/Gson, and always handle network failures, timeouts, and error codes.
That completes Stage 3! You can now handle errors, wield collections and generics, work with files and time, and talk to the network. Stage 4 takes you into advanced territory: concurrency, functional programming, and the JVM itself.