Since Java 1.6, there's a builtin HTTP server in Sun Oracle JDK (note: JDK, not JRE). The com.sun.net.httpserver
package summary outlines the involved classes and contains examples.
Here's a (basic) kickoff example based on the docs, you can just copy'n'paste'n'run it on Java 1.6
package com.example;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
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
server.start();
}
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();
os.write(response.getBytes());
os.close();
}
}
}
Execute it and go to http://localhost:8000/test
and you'll see the following response:
This is the response
Note that this is, in contrary to what some naive developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.*
package (such as sun.misc.BASE64Encoder
) for internal usage by the Oracle JRE, not the com.sun.*
package. Sun/Oracle also just develops software on top of the Java SE API themselves like as every other company such as Apache and so on.