HTTP
HTTP is the request-and-response protocol the web runs on. A client sends a request made of a method, a path, some headers and an optional body, and the server sends back a status code, headers and a body.
Detailed Explanation
Strip away the tooling and HTTP is a conversation with strict grammar. The client says "GET /orders/42, and I would like JSON". The server says "200, here is JSON, it is 318 bytes long". Then the exchange is over. That is the entire protocol.
HTTP exists because the alternative was chaos. Before it, every networked application invented its own wire format: its own way of marking where one message ended and the next began, its own error signalling, its own authentication. None of it was reusable. HTTP standardised the envelope, so a browser, a mobile app, curl and a Java service can all talk to the same server without prior agreement about anything except the URL.
A request has four parts. The method states the intent. The path names the resource. The headers carry metadata such as Content-Type and Authorization. The body carries the payload, and most methods may omit it. The response mirrors that shape, with a status code in place of the method.
The methods carry promises that infrastructure relies on:
| Method | Safe (no change) | Idempotent (repeat is harmless) |
|---|---|---|
GET | yes | yes |
PUT | no | yes |
DELETE | no | yes |
POST | no | no |
That last row matters in production. A retried POST can create two orders, which is why payment endpoints need an idempotency key.
HTTP is stateless. The server remembers nothing about you between requests. Identity has to travel on every single request, either as a cookie (Java's servlet session cookie is JSESSIONID) or as a bearer token in the Authorization header. Statelessness is what lets you put ten copies of your service behind a load balancer without them needing to gossip.
As a Java developer you almost never parse HTTP yourself. A servlet container does it: Tomcat, Jetty or Undertow accepts the TCP connection, reads the bytes, validates the framing, and hands your code an HttpServletRequest object with the method, headers and body already decoded. Spring Boot embeds Tomcat by default, so that container is inside your JAR rather than a server you deploy into.
The cost is mostly threads. The classic servlet model is thread-per-request: one platform thread is dedicated to your request and stays parked while you wait on a database. Tomcat's default ceiling of 200 threads therefore caps in-flight requests at roughly 200, and each thread reserves around a megabyte of stack. Java 21 virtual threads change that arithmetic, because a parked virtual thread costs a few hundred bytes instead of a megabyte.
On the outbound side, use java.net.http.HttpClient, added in Java 11. It replaced the awkward HttpURLConnection, speaks HTTP/2, and pools connections so you avoid a fresh TCP and TLS handshake per call.
Code Examples
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class OrderLookup {
// HttpClient is thread-safe and pools connections.
// Create ONE per application and share it. A new client per call leaks sockets and threads.
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5)) // limit on opening the TCP connection only
.followRedirects(HttpClient.Redirect.NORMAL) // follow 3xx, but never https -> http
.build();
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/orders/42"))
.header("Accept", "application/json") // which representation we want back
.timeout(Duration.ofSeconds(10)) // limit on the whole exchange, not per byte
.GET()
.build();
// A BodyHandler decides how response bytes become a Java value.
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
System.out.println(response.version()); // HTTP_2 when the server negotiated it
System.out.println(response.headers().firstValue("content-type").orElse("absent"));
System.out.println(response.body());
}
}GET /orders/42 HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi...
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 52
{"id":42,"total":19.99,"status":"SHIPPED"}Common Gotchas
A body without a `Content-Type` header
the server cannot tell whether your `POST` bytes are JSON, form data or a file, so it refuses the request with `415 Unsupported Media Type`. `HttpRequest.BodyPublishers.ofString(...)` does not set the header for you; add `.header("Content-Type", "application/json")` yourself.
Building a new `HttpClient` per request
each instance owns a connection pool and a selector thread. Creating one in a loop exhausts file descriptors under load and throws away every keep-alive connection you paid a TLS handshake for. Hold it in a `static final` field or a Spring bean.
Retrying a `POST` blindly
`POST` is not idempotent, so an automatic retry after a timeout can duplicate a charge or an order. The first request may well have succeeded and only the response was lost. Retry `GET`, `PUT` and `DELETE` freely; guard `POST` with an idempotency key the server deduplicates on.
HTTP/2 changes performance, not semantics
it multiplexes many requests over one TCP connection and compresses headers, so the old trick of sharding assets across hostnames now hurts. Your methods, status codes and headers mean exactly what they did on HTTP/1.1.