Skip to content

Instantly share code, notes, and snippets.

@fcarriedo
Created September 6, 2011 21:20
Show Gist options
  • Save fcarriedo/1199002 to your computer and use it in GitHub Desktop.
Save fcarriedo/1199002 to your computer and use it in GitHub Desktop.
Minimal jdk1.6 java http server. Sun's Internal.
import com.sun.net.httpserver.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class DemoServer {
public static void main(String[] args) throws Exception {
final int port = 8000;
HttpServer server = HttpServer.create( new InetSocketAddress("localhost", port), 10);
server.createContext("/stats", new MyHandler());
System.out.println("Server starting on port: " + port);
server.start();
}
}
class MyHandler implements HttpHandler {
private int hits;
public void handle(HttpExchange t) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(t.getRequestBody()));
String line;
StringBuilder reqBody = new StringBuilder();
while( (line = in.readLine()) != null ) {
reqBody.append(line);
}
System.out.println("Method: " + t.getRequestMethod() + ". Body: " + reqBody.toString());
Map<String,String> params = parse( reqBody.toString() );
String str = "Hello World! " + (++hits);
t.sendResponseHeaders(200, str.length());
t.getResponseBody().write(str.getBytes());
t.getResponseBody().close();
t.close();
}
private Map<String,String> parse(String reqBody) {
String[] elems = reqBody.split("&");
Map<String,String> params = new HashMap<String,String>();
for(String paramPair : elems) {
String[] pair = paramPair.split("=");
params.put(pair[0], pair[1]);
}
return params;
}
}
@fcarriedo
Copy link
Author

Use this just for quick prototyping. Don't base your company on this one since com.sun.net.httpserver may be going out in the short term since they are not standard java packages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment