Tuesday, January 24, 2006

Mustang's HTTP Server

Alan Bateman has kindly provided me with a link to the HTTP server API documentation. This will soon be hooked up in the Mustang docs.

Several times, I've seen Mustang's inclusion of an HTTP server mentioned. A technical article points to bug 6270015, which asks for support of a lightweight HTTP server API. This bug is marked "closed, fixed". Yet, you won't find anything in the Mustang JavaDoc on it. What's the deal? Well, if we read carefully, Mustang will include an HTTP server API, not JSE 6. If we follow David Herrons recommendation, we should therefore forget about this quickly.

However, that API looks like it had some thinking put into it, is documented and itself distinguishes thoroughly between com.sun.* (sort-of presentable?) and sun.* (don't go there?) packages. Here's how you run a simple server:

HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 5);
httpServer.createContext("/", new HttpHandler() {
public void handle(final HttpExchange exchange) throws IOException {
Headers requestHeaders = exchange.getRequestHeaders();
exchange.getResponseHeaders().set("Content-Type", "text/plain;charset=utf-8");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(responseBody, "UTF-8"));
for (Map.Entry> entry : requestHeaders.entrySet())
printWriter.println(entry.getKey() + ": " + entry.getValue());

printWriter.close();
}
});

// the server will be single-threaded unless you uncomment this line
// httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();

Simple enough. If this thing sur

No comments: