HTTP Basics in Java
HTTP (Hypertext Transfer Protocol) is the text-based protocol that browsers, mobile apps and servers use to talk to each other. Every Java web technology, from servlets to Spring Boot, is built on top of it. Learning HTTP basics in Java first makes the later web lessons much easier, because a servlet is simply Java code that reads an HTTP request and writes an HTTP response.
This lesson uses two tools that ship with the JDK: the small com.sun.net.httpserver.HttpServer to play the server, and curl or java.net.http.HttpClient to play the client. No libraries or containers are needed.
How HTTP Works: Request and Response
HTTP is a request–response protocol. The client opens a TCP connection, sends one request, and the server sends back one response.
Client (browser, curl, HttpClient) Server (Tomcat, HttpServer)
| |
| GET /hello HTTP/1.1 |
| Host: localhost:8000 |
|--------------------------------------------->|
| |
| HTTP/1.1 200 OK |
| Content-Type: text/plain |
| Hello from Java HTTP! |
|<---------------------------------------------|
| Part | Request | Response |
|---|---|---|
| First line | Method, path, version: GET /hello HTTP/1.1 | Version, status code, reason: HTTP/1.1 200 OK |
| Headers | Name: value lines, such as Host and Accept | Name: value lines, such as Content-Type |
| Blank line | Ends the headers | Ends the headers |
| Body | Optional (form data, JSON) | Optional (HTML, JSON, images) |
How it works:
- HTTP/1.1 messages are plain text lines ending in
\r\n. HTTP/2 and HTTP/3 send the same information in a binary format, but the methods, headers and status codes are identical. - HTTP runs over TCP, the same kind of connection you used in Java Socket. HTTPS is HTTP inside an encrypted TLS connection.
Create a Simple HTTP Server in Java
The JDK includes a lightweight HTTP server in the jdk.httpserver module. It is ideal for learning, tests and small tools.
// HelloHttpServer.java
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class HelloHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/hello", exchange -> {
byte[] body = "Hello from Java HTTP!\n".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.sendResponseHeaders(200, body.length); // status + body length
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
});
server.start();
System.out.println("Listening on http://localhost:8000/hello");
}
}
Run it and call it with curl -i, which prints the response headers too:
java HelloHttpServer.java
curl -i http://localhost:8000/hello
Output:
HTTP/1.1 200 OK
Date: Tue, 17 Nov 2026 12:30:00 GMT
Content-type: text/plain; charset=utf-8
Content-length: 22
Hello from Java HTTP!
How it works:
createContext("/hello", handler)maps a path to a handler. The handler receives anHttpExchange, which holds both the request and the response.sendResponseHeaders(200, length)writes the status line and headers. After that you can only write the body.- The server adds
DateandContent-lengthitself. It prints header names with only the first letter in capitals (Content-type), which is allowed because HTTP header names are case-insensitive. java HelloHttpServer.javacompiles and runs a single source file in one step.
Read the Parts of an HTTP Request
The next handler prints the request line and every header, so you can see exactly what a client sends. Add it, and the other handlers in this lesson, to HelloHttpServer before server.start().
server.createContext("/echo", exchange -> {
System.out.println(exchange.getRequestMethod() + " "
+ exchange.getRequestURI() + " " + exchange.getProtocol());
// TreeMap sorts header names so the output is easy to read
new java.util.TreeMap<>(exchange.getRequestHeaders())
.forEach((name, values) -> System.out.println(name + ": " + String.join(", ", values)));
exchange.sendResponseHeaders(204, -1); // 204 No Content, no body
exchange.close();
});
curl http://localhost:8000/echo?course=java
Output in the server terminal:
GET /echo?course=java HTTP/1.1
Accept: */*
Host: localhost:8000
User-agent: curl/8.5.0
How it works:
- The request line has three parts: the method (
GET), the request target (/echo?course=java) and the protocol version. Hostis required in HTTP/1.1. It lets one server host many websites on the same IP address.- A length of
-1insendResponseHeadersmeans "no body", which is correct for status204.
HTTP Methods
The method tells the server what the client wants to do with the resource named in the path.
| Method | Purpose | Has body? | Safe | Idempotent |
|---|---|---|---|---|
GET | Read a resource | No | Yes | Yes |
POST | Create a resource or submit data | Yes | No | No |
PUT | Replace a resource completely | Yes | No | Yes |
PATCH | Change part of a resource | Yes | No | No |
DELETE | Remove a resource | Usually no | No | Yes |
HEAD | Same as GET but headers only | No | Yes | Yes |
OPTIONS | Ask which methods are allowed | No | Yes | Yes |
How it works:
- Safe means the request does not change data on the server. Browsers and crawlers may send safe requests freely.
- Idempotent means sending the same request twice has the same effect as sending it once. Deleting student 7 twice still leaves student 7 deleted, but posting the same order twice creates two orders.
The handler below reacts differently to each method:
server.createContext("/method", exchange -> {
String reply = switch (exchange.getRequestMethod()) {
case "GET" -> "You asked to read data";
case "POST" -> "You sent new data";
case "DELETE" -> "You asked to delete data";
default -> "Method not handled";
};
byte[] body = (reply + "\n").getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) { out.write(body); }
});
curl http://localhost:8000/method
curl -X POST http://localhost:8000/method
curl -X DELETE http://localhost:8000/method
Output:
You asked to read data
You sent new data
You asked to delete data
How it works:
curl -Xsets the method. Without it, curl sendsGET.getRequestMethod()returns the method name in capitals, so aswitchon strings works well.
HTTP Status Codes
The status code is a three-digit number that tells the client how the request went. The first digit gives the category.
| Range | Meaning | Common codes |
|---|---|---|
1xx | Informational | 101 Switching Protocols (WebSocket upgrade) |
2xx | Success | 200 OK, 201 Created, 204 No Content |
3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
4xx | Client error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed |
5xx | Server error | 500 Internal Server Error, 503 Service Unavailable |
Use HttpClient to check the status of several paths:
// StatusCheck.java (run while HelloHttpServer is running)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class StatusCheck {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
for (String path : new String[] {"/hello", "/echo", "/missing"}) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8000" + path)).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(path + " -> " + response.statusCode());
}
}
}
Output:
/hello -> 200
/echo -> 204
/missing -> 404
How it works:
HttpServeranswers404by itself when no context matches the path.BodyHandlers.discarding()ignores the body, because only the status is needed. The full client API is covered in Java HttpClient.
Note: A
4xxcode means the client must change the request. A5xxcode means the server failed, and the same request may work later.
HTTP Headers
Headers carry extra information about the message. Some describe the body, some control caching, and some identify the client.
| Header | Sent by | Example | Meaning |
|---|---|---|---|
Content-Type | Both | application/json; charset=utf-8 | Format of the body |
Content-Length | Both | 42 | Body size in bytes |
Accept | Client | application/json | Formats the client can read |
User-Agent | Client | curl/8.5.0 | Client software |
Authorization | Client | Bearer abc123 | Credentials |
Location | Server | /students/4 | Where a new or moved resource is |
Cache-Control | Server | no-store | Caching rules |
Set-Cookie / Cookie | Server / Client | visits=3 | Small state stored in the browser |
The handler below chooses the format from the Accept header:
server.createContext("/course", exchange -> {
String accept = exchange.getRequestHeaders().getFirst("Accept");
boolean wantsJson = accept != null && accept.contains("application/json");
String body = wantsJson ? "{\"course\":\"Java\",\"lessons\":306}\n" : "Course: Java (306 lessons)\n";
String type = wantsJson ? "application/json" : "text/plain";
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", type + "; charset=utf-8");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); }
});
curl http://localhost:8000/course
curl -H "Accept: application/json" http://localhost:8000/course
Output:
Course: Java (306 lessons)
{"course":"Java","lessons":306}
How it works:
getFirst("Accept")returns the first value of the header, ornullif the client did not send it. The lookup ignores case.- Choosing the response format from
Acceptis called content negotiation.
Query Strings and URL Encoding
Data in a URL goes after ? as name=value pairs joined by &. Special characters must be percent-encoded.
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
public class QueryStringDemo {
public static void main(String[] args) {
String encoded = URLEncoder.encode("Java & Spring", StandardCharsets.UTF_8);
System.out.println("Encoded: " + encoded);
String query = "course=" + encoded + "&level=beginner";
System.out.println("Query: " + query);
System.out.println("Parsed: " + parseQuery(query));
}
static Map<String, String> parseQuery(String query) {
Map<String, String> params = new LinkedHashMap<>();
for (String pair : query.split("&")) {
String[] parts = pair.split("=", 2);
String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8);
String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "";
params.put(name, value);
}
return params;
}
}
Output:
Encoded: Java+%26+Spring
Query: course=Java+%26+Spring&level=beginner
Parsed: {course=Java & Spring, level=beginner}
How it works:
URLEncoderturns&into%26and spaces into+, so the value cannot be confused with the separators.URLDecoderreverses this. Servlets do this parsing for you throughrequest.getParameter(...), as shown in HttpServletRequest in Java.
Request Bodies and Content-Type
POST, PUT and PATCH usually send data in the body. The Content-Type header tells the server how to read it.
| Content-Type | Body looks like | Typical sender |
|---|---|---|
application/x-www-form-urlencoded | name=Asha&course=Java | HTML forms |
multipart/form-data | Parts separated by a boundary | Forms with file uploads |
application/json | {"name":"Asha"} | JavaScript and API clients |
text/plain | Any text | Simple tools |
server.createContext("/submit", exchange -> {
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String reply = "Type: " + contentType + "\nBody: " + body + "\n";
byte[] bytes = reply.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); }
});
curl -d "name=Asha&course=Java" http://localhost:8000/submit
curl -H "Content-Type: application/json" -d '{"name":"Ravi"}' http://localhost:8000/submit
Output:
Type: application/x-www-form-urlencoded
Body: name=Asha&course=Java
Type: application/json
Body: {"name":"Ravi"}
How it works:
curl -dsends aPOSTwith a form-encoded body by default. Adding-H "Content-Type: ..."changes the declared type.getRequestBody()returns anInputStream.readAllBytes()reads the whole body, which is fine for small requests.
Cookies and Stateless HTTP
HTTP is stateless: each request stands alone, and the server does not remember the previous one. Cookies add memory. The server sends Set-Cookie, and the client returns the value in a Cookie header on later requests.
server.createContext("/visits", exchange -> {
int visits = 0;
String cookieHeader = exchange.getRequestHeaders().getFirst("Cookie");
if (cookieHeader != null) {
for (String cookie : cookieHeader.split(";\\s*")) {
if (cookie.startsWith("visits=")) {
visits = Integer.parseInt(cookie.substring("visits=".length()));
}
}
}
visits++;
exchange.getResponseHeaders().add("Set-Cookie", "visits=" + visits + "; Path=/; HttpOnly");
byte[] bytes = ("Visit number " + visits + "\n").getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); }
});
// VisitClient.java: the CookieManager stores and resends cookies like a browser
import java.net.CookieManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class VisitClient {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder().cookieHandler(new CookieManager()).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8000/visits")).build();
for (int i = 0; i < 3; i++) {
System.out.print(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
}
}
}
Output:
Visit number 1
Visit number 2
Visit number 3
How it works:
- The first request has no cookie, so the count starts at 1 and the server sets
visits=1. CookieManagersaves the cookie and addsCookie: visits=1to the next request, and so on. Without it, every call would print "Visit number 1".HttpOnlystops JavaScript in a browser from reading the cookie. Servlets build sessions on this same mechanism with aJSESSIONIDcookie.
Real-World Example: HTTP Basics in Java With a Small Student API
This server combines methods, status codes, headers, query strings and JSON bodies into a small REST-style API. It returns 201 Created with a Location header for new students and 405 with an Allow header for unsupported methods.
// StudentApiServer.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class StudentApiServer {
private static final Map<Integer, String> students = new ConcurrentHashMap<>();
private static final AtomicInteger nextId = new AtomicInteger(1);
private static final Pattern NAME_FIELD = Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\"");
public static void main(String[] args) throws IOException {
students.put(nextId.getAndIncrement(), "Asha");
students.put(nextId.getAndIncrement(), "Ravi");
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/students", StudentApiServer::handleStudents);
server.setExecutor(Executors.newFixedThreadPool(4)); // handle 4 requests at once
server.start();
System.out.println("Student API on http://localhost:8000/students");
}
private static void handleStudents(HttpExchange exchange) throws IOException {
switch (exchange.getRequestMethod()) {
case "GET" -> listOrFind(exchange);
case "POST" -> create(exchange);
default -> {
exchange.getResponseHeaders().set("Allow", "GET, POST");
sendJson(exchange, 405, "{\"error\":\"Method not allowed\"}");
}
}
}
private static void listOrFind(HttpExchange exchange) throws IOException {
String query = exchange.getRequestURI().getQuery(); // e.g. "id=2" or null
if (query != null && query.startsWith("id=")) {
int id = Integer.parseInt(query.substring(3));
String name = students.get(id);
if (name == null) {
sendJson(exchange, 404, "{\"error\":\"Student " + id + " not found\"}");
} else {
sendJson(exchange, 200, toJson(id, name));
}
return;
}
String all = students.entrySet().stream()
.map(entry -> toJson(entry.getKey(), entry.getValue()))
.collect(Collectors.joining(",", "[", "]"));
sendJson(exchange, 200, all);
}
private static void create(HttpExchange exchange) throws IOException {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Matcher matcher = NAME_FIELD.matcher(body);
if (!matcher.find()) {
sendJson(exchange, 400, "{\"error\":\"Body must contain a name\"}");
return;
}
int id = nextId.getAndIncrement();
students.put(id, matcher.group(1));
exchange.getResponseHeaders().set("Location", "/students?id=" + id);
sendJson(exchange, 201, toJson(id, matcher.group(1)));
}
private static String toJson(int id, String name) {
return "{\"id\":" + id + ",\"name\":\"" + name + "\"}";
}
private static void sendJson(HttpExchange exchange, int status, String json) throws IOException {
byte[] bytes = (json + "\n").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
}
Try every path with curl:
java StudentApiServer.java
curl -s http://localhost:8000/students
curl -s "http://localhost:8000/students?id=2"
curl -s -i -X POST -H "Content-Type: application/json" -d '{"name":"Meena"}' http://localhost:8000/students
curl -s -w " (%{http_code})\n" "http://localhost:8000/students?id=9"
curl -s -w " (%{http_code})\n" -d '{}' http://localhost:8000/students
curl -s -i -X DELETE http://localhost:8000/students | head -n 1
Output (Date headers removed):
[{"id":1,"name":"Asha"},{"id":2,"name":"Ravi"}]
{"id":2,"name":"Ravi"}
HTTP/1.1 201 Created
Location: /students?id=3
Content-type: application/json; charset=utf-8
Content-length: 24
{"id":3,"name":"Meena"}
{"error":"Student 9 not found"}
(404)
{"error":"Body must contain a name"}
(400)
HTTP/1.1 405 Method Not Allowed
How it works:
- One path, several methods.
/studentssupportsGETfor reading andPOSTfor creating. Any other method gets405plus anAllowheader that lists the valid ones. - Correct status codes. A missing student returns
404, a bad body returns400, and a new student returns201 Createdwith aLocationheader that points to it. - Query string lookup.
getRequestURI().getQuery()returns the text after?, which selects a single student. - Thread-safe data.
setExecutorgives the server a pool of four threads, so requests can run at the same time. The data therefore lives in aConcurrentHashMapand IDs come from anAtomicInteger. - JSON responses. Every reply sets
Content-Type: application/json, so clients know how to read the body. In the next lesson, Java Servlet Basics, the same ideas run inside Tomcat, which parses parameters and manages threads for you.