05 - Servidor HTTP del JDK
HttpServer del JDK
A partir de Java 6, el JDK incluye un servidor HTTP muy sencillo de usar:
- Se encuentra en el paquete `com.sun.net.httpserver`.
- Permite crear un servidor HTTP sin librerías externas.
- Gestiona múltiples clientes automáticamente mediante hilos.
- Se pueden definir handlers para distintas rutas.
Código básico
HttpServerJdk
package es.cesguiro.socket; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; public class HttpServerJdk { private final int port = 8080; public void start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); System.out.println("HTTP server started on port " + port); // Un único handler que sirve archivos desde resources/www server.createContext("/", new FileHandler()); server.setExecutor(null); // usa el executor por defecto server.start(); } static class FileHandler implements HttpHandler { @Override public void handle(HttpExchange exchange) throws IOException { String path = exchange.getRequestURI().getPath(); // Mapear "/" a index.html if (path.equals("/")) { path = "/index.html"; } // Leer el archivo desde resources/www InputStream is = getClass().getResourceAsStream("/www" + path); if (is == null) { String notFound = "<h1>404 Not Found</h1>"; exchange.sendResponseHeaders(404, notFound.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(notFound.getBytes()); os.close(); return; } // Leer el contenido del archivo byte[] content = is.readAllBytes(); exchange.sendResponseHeaders(200, content.length); OutputStream os = exchange.getResponseBody(); os.write(content); os.close(); } } }
Main
package es.cesguiro.socket; import java.io.IOException; public class Main { public static void main(String[] args) { HttpServerJdk server = new HttpServerJdk(); try { server.start(); } catch (IOException e) { e.printStackTrace(); } } }
Ventajas frente a nuestro mini servidor
- No hay que gestionar sockets ni hilos manualmente.
- Permite definir rutas específicas con handlers.
- Se puede extender para servir ficheros estáticos o crear APIs REST.
- Ideal para pruebas y prototipos antes de usar un contenedor como Tomcat.
Ejecución
- Arranca `Main.java`.
- Accede en el navegador:
- http://localhost:8080/ → ruta `/`
- http://localhost:8080/about → ruta `/about`