Atom Feed SITE FEED   ADD TO GOOGLE READER

MiniHttpServer.java - an HTTP Server in 168 lines

For part of an project which I'll be announcing shortly, I needed an extremely lightweight HTTP server. Fortunately, HTTP is quite easy-to-implement. Tonight I hacked together MiniHttpServer.java, a simple server with zero third-party dependencies.

I was able to support the core of HTTP in with just 168 lines by doing only the bare-minimum. Here's the server's core:
        nextLine();
readUntil("GET\\s+");
String url = readUntil("\\s+HTTP/1.1");

do {
nextLine();
} while (readUntil("$").length() > 0);

InputStream responseData = handler.getResponse(url);
if (responseData != null) {
write("HTTP/1.1 200 OK\r\n\r\n");
int b;
while ((b = responseData.read()) != -1) {
connection.getOutputStream().write(b);
}

} else {
write("HTTP/1.1 404 Not Found\r\n\r\n");
write("404 Not Found: " + url);

}

connection.close();

If you need an embedded HTTP server, please help yourself to this code. It's fully open source, and available under your choice of Mozilla 1.1 or LGPL license.
In Java 6 you can just use the one built into the JDK:

http://blogs.sun.com/michaelmcm/entry/http_server_api_in_java

:)

Sam
Neato - I had no idea about the HTTP server in Sun's JRE. This will probably be quite useful for prototyping!

Of course, it won't work for me since I don't want to be tied to a particular JRE. I'd like my code to work on Android, for example.