Skip to content

Instantly share code, notes, and snippets.

@lawrenceching
Created March 26, 2021 18:19
Show Gist options
  • Save lawrenceching/2b60de733602707820d91a3574f32495 to your computer and use it in GitHub Desktop.
Save lawrenceching/2b60de733602707820d91a3574f32495 to your computer and use it in GitHub Desktop.
The build-in, simplest HTTP server in Java,
package me.imlc.demos;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class JavaHttpServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hello", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String resp = "Hello, world!";
exchange.sendResponseHeaders(200, resp.length());
OutputStream os = exchange.getResponseBody();
os.write(resp.getBytes());
os.close();
}
});
server.setExecutor(null);
server.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment