Skip to content

Instantly share code, notes, and snippets.

@DALDEI
Created March 12, 2017 12:49
Show Gist options
  • Save DALDEI/1608138ec8e885eb89ef1e592d91c623 to your computer and use it in GitHub Desktop.
Save DALDEI/1608138ec8e885eb89ef1e592d91c623 to your computer and use it in GitHub Desktop.
Minimal HTTP Server using com.sun.net.httpserver.HttpServer
// from: http://www.rgagnon.com/javadetails/java-have-a-simple-http-server.html
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;
/*
* a simple static http server
*/
public class SimpleHttpServer {
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 = "Welcome Real's HowTo test page";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.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