Skip to content

Instantly share code, notes, and snippets.

@lloydroc
Created July 20, 2018 13:39
Show Gist options
  • Save lloydroc/26e44bb9694e0f9c4360ab405f65ffed to your computer and use it in GitHub Desktop.
Save lloydroc/26e44bb9694e0f9c4360ab405f65ffed to your computer and use it in GitHub Desktop.
Simple Java HTTP Server
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;
public class SimpleServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
SimpleServer ss = new SimpleServer();
HelloHandler hh = ss.new HelloHandler();
server.createContext("/hello", hh);
server.setExecutor(null);
server.start();
}
class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "Hello World";
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