Simple HTTP server in Java (using Sun httpserver)


This code may be not safe for production! Use with warning.

What and why?

What? Super simple HTTP implementation in Java, for building simple backend for websites or web API's. Using Sun Microsystems packages, still works in OpenJDK 14.0.2 (At least tested, should work in newer versions too). Why? Becouse I don't want to install any third party packages, and it's just easier that way.

Code origin

I have found this code in StackOverflow answer made by user BalusC, so huge thanks for that. However, he says in this answer, that code he posted is straight from Oracle documentation. Code is not mine, all rights belong to its author.

The code



public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();


Tested on:

# Ubuntu Server
d3s@usorolabs:~/javasun$ java --version
openjdk 14.0.2 2020-07-14
OpenJDK Runtime Environment (build 14.0.2+12-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 14.0.2+12-Ubuntu-120.04, mixed mode, sharing)

# IntelliJ IDEA Community
AdoptOpenJDK 11.0.10 (HotSpot)
AdoptOpenJDK 1.8.0_282 (HotSpot)

# Oracle Solaris 11.4
d3s@solaris:~$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b12, mixed mode)

Additional Links documentation