Tiny web server (zero dependencies)
A lightweight HTTP server built with Java's built-in 'HttpServer'
How It Works
The web server uses Java’s com.sun.net.httpserver.HttpServer to create a lightweight HTTP server that:
- Listens on a specified port (default: 9999)
- Maps URL paths to JSON response files stored in the responses/ directory
- Serves the file contents as the JSON response body with a custom HTTP status
How To Create A Web Server
Project Structure
responses
users.json
user.json
user_not_found.json
src
WebServer.java
Code Snippets
WebServer.java:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
void main() throws Exception {
var server = HttpServer.create(new InetSocketAddress(9999), 0);
server.createContext("/api/rest/v1/users/12345",
exchange -> readFromFile(exchange, "responses/user.json", 200));
server.createContext("/api/rest/v1/users/54321",
exchange -> readFromFile(exchange, "responses/user_not_found.json", 404));
server.start();
IO.println("Serving on http://localhost:9999/api/rest/v1/users/12345");
IO.println("Serving on http://localhost:9999/api/rest/v1/users/54321");
}
private static void readFromFile(HttpExchange exchange, String path,
int responseStatus) throws IOException {
byte[] body = Files.readAllBytes(Path.of(path));
exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
exchange.sendResponseHeaders(responseStatus, body.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(body);
}
exchange.close();
}
Adding New Endpoints
To add a new endpoint:
-
Create a JSON response body file in the responses/ directory:
{ "users": [ {"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Smith"} ] } -
Add the endpoint mapping in WebServer.java:
server.createContext("/api/rest/v2/users/all", exchange -> readFromFile(exchange, "responses/users.json")); -
Add a console log (optional but recommended):
IO.println("Serving web server on http://localhost:9999/api/users"); -
Restart the server