Skip to content

Instantly share code, notes, and snippets.

@towc
Created October 14, 2018 19:21
Show Gist options
  • Select an option

  • Save towc/ab02368f1ed9b66b23aa732f85418f7e to your computer and use it in GitHub Desktop.

Select an option

Save towc/ab02368f1ed9b66b23aa732f85418f7e to your computer and use it in GitHub Desktop.
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
Server server = new Server();
server.register("/", new HandleRoot());
server.register("/abc", new HandleAbc());
server.start();
}
}
public class HandleAbc extends Handler {
private int num = 0;
public String handle() {
return "" + (num++);
}
}
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
public class Handler {
public Handler() {
}
public String handle() {
return "";
}
}
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
public class HandleRoot extends Handler {
public String handle() {
return "hi there";
}
}
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.HashMap;
public class Server {
private HttpServer http;
private HttpContext ctx;
private HashMap<String, Handler> handlers = new HashMap<>();
public Server() throws IOException {
http = HttpServer.create(new InetSocketAddress(8500), 0);
ctx = http.createContext("/");
ctx.setHandler(this::handleRequest);
}
public void register(String path, Handler handler) {
handlers.put(path, handler);
}
public void start() {
http.start();
}
private void handleRequest(HttpExchange conn) throws IOException {
URI pathURI = conn.getRequestURI();
String path = pathURI.toString();
System.out.println(path);
Handler handler = handlers.get(path);
String response = handler.handle();
conn.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = conn.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment