Skip to content

Instantly share code, notes, and snippets.

@kalaspuffar
Created February 9, 2020 20:34
Show Gist options
  • Save kalaspuffar/87aa9e3081110359daac03f16ce45e96 to your computer and use it in GitHub Desktop.
Save kalaspuffar/87aa9e3081110359daac03f16ce45e96 to your computer and use it in GitHub Desktop.
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import sun.net.httpserver.HttpServerImpl;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class HttpServerExample {
public static void main(String[] args) {
try {
HttpServer httpServer = HttpServerImpl.create(new InetSocketAddress(8080), 0);
HttpContext hc = httpServer.createContext("/", new HttpHandler() {
public void handle(HttpExchange httpExchange) throws IOException {
String s = "<h1>Hello world. This is my small implementation of an Java web server.</h1>";
httpExchange.sendResponseHeaders(200, s.length());
OutputStream os = httpExchange.getResponseBody();
os.write(s.getBytes());
os.close();
}
});
httpServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment