Skip to content

Instantly share code, notes, and snippets.

@prashant-shahi
Created June 5, 2023 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prashant-shahi/395e5a59efc85229d2647437e0b88d00 to your computer and use it in GitHub Desktop.
Save prashant-shahi/395e5a59efc85229d2647437e0b88d00 to your computer and use it in GitHub Desktop.
Simple HTTP Server in Java
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 SimpleHttpServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hello", new HelloHandler());
server.setExecutor(null);
server.start();
System.out.println("Server is listening on port 8080");
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello, World!";
exchange.sendResponseHeaders(200, response.length());
OutputStream outputStream = exchange.getResponseBody();
outputStream.write(response.getBytes());
outputStream.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment