Sunday, 8 October 2017

java SE - simple HttpServer


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public final class Server {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            printUsage();
            System.exit(0);
        }
        Server s = new Server("localhost", 8080);
        s.start(Paths.get(args[0]), true);
    }

    private static void printUsage() {
        String usage = "" + "usage: java Server [zipfile/folder]"
        /**
         * + " [options] \n\n" 
         * +"options:\n" 
         * + "--port          Port to use [8080]" 
         * + "--address       Address to use [localhost]"
         */
        ;

        System.out.println(usage);
    }

    private static final URI ROOT_URI;

    static {
        URI u = null;
        try {
            u = new URI("/");
        } catch (URISyntaxException e) {
        }
        ROOT_URI = u;
    }

    private Path rootFolder;
    private final HttpServer hs;
    private final int port;

    public Server(String address, int port) throws IOException {
        this.port = port;
        hs = HttpServer.create(new InetSocketAddress(address, port), 10);

        hs.createContext(ROOT_URI.toString(), new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                URI uri = exchange.getRequestURI();

                Path p = rootFolder.resolve(uri.equals(ROOT_URI) ? "index.html" : uri.getPath().substring(1));
                System.out.println(uri);

                if (Files.notExists(p))
                    exchange.sendResponseHeaders(404, -1);
                else {
                    exchange.getResponseHeaders().add("Content-Type",
                            Optional.ofNullable(Files.probeContentType(p)).orElse("text/plain"));
                    exchange.sendResponseHeaders(200, Files.size(p));
                    OutputStream os = exchange.getResponseBody();
                    Files.copy(p, os);
                    os.close();
                }
            }
        });
    }

    private void start(Path rootFolder, boolean openInBrowser) throws IOException {
        this.rootFolder = rootFolder;

        hs.start();
        System.out.println("server running at: localhost:" + port);
        if (openInBrowser)
            Runtime.getRuntime().exec("explorer http://localhost:" + port);

    }
}

also see: java SE - not so Simple HttpServer

No comments:

Post a Comment