Java Built-in HTTP Server
Create a lightweight HTTP server with com.sun.net.httpserver: routing, JSON responses, file serving.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.Executors;
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.setExecutor(Executors.newFixedThreadPool(10));
// JSON endpoint
server.createContext("/api/hello", exchange -> {
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "{\"error\": \"Method not allowed\"}");
return;
}
String name = getQueryParam(exchange, "name", "World");
String json = "{\"message\": \"Hello, " + name + "!\"}"; // Use a JSON lib in production
exchange.getResponseHeaders().set("Content-Type", "application/json");
sendResponse(exchange, 200, json);
});
// POST endpoint — read body
server.createContext("/api/echo", exchange -> {
if (!"POST".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "POST only");
return;
}
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain");
sendResponse(exchange, 200, "Echo: " + body);
});
// Health check
server.createContext("/health", exchange -> {
sendResponse(exchange, 200, "{\"status\": \"UP\"}");
});
server.start();
System.out.println("Server running on http://localhost:8080");
}
static void sendResponse(HttpExchange exchange, int status, String body)
throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
static String getQueryParam(HttpExchange exchange, String key, String defaultVal) {
String query = exchange.getRequestURI().getQuery();
if (query == null) return defaultVal;
for (String param : query.split("&")) {
String[] kv = param.split("=", 2);
if (kv[0].equals(key) && kv.length > 1) return kv[1];
}
return defaultVal;
}
}Sponsored
Railway
Use Cases
- Lightweight HTTP servers for testing and prototyping
- Embedded health check endpoints
- Simple API servers without external frameworks
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
Java HttpClient — GET and POST Requests
Make HTTP requests with Java 11+ HttpClient: GET, POST JSON, async calls, and response handling.
Best for: Calling REST APIs from Java applications
Rate Limiter — Token Bucket Algorithm
Implement a thread-safe rate limiter using the token bucket algorithm for API throttling.
Best for: API rate limiting per user or IP
Spring Boot — RestClient HTTP Calls
Make HTTP requests with Spring RestClient (6.1+): GET, POST, error handling, interceptors, and timeouts.
Best for: REST API consumption in Spring Boot services