Tabla de Contenidos

05 - Servidor HTTP del JDK

HttpServer del JDK

A partir de Java 6, el JDK incluye un servidor HTTP muy sencillo de usar:

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

Ejecución

  1. Arranca `Main.java`.

  2. Accede en el navegador: