Skip to content

Instantly share code, notes, and snippets.

@isicju
Last active October 23, 2024 06:40
Show Gist options
  • Save isicju/ead8e7b1d7737e86d692e8d2da45a9cf to your computer and use it in GitHub Desktop.
Save isicju/ead8e7b1d7737e86d692e8d2da45a9cf to your computer and use it in GitHub Desktop.
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.UUID;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class UuidHttpServer {
public static void main(String[] args) throws IOException {
// Create the HTTP server on port 8000
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
// Set a context that responds to "/uuid" with a UUID
server.createContext("/uuid", new UuidHandler());
server.setExecutor(null); // creates a default executor
server.start();
System.out.println("Server is listening on port 8000...");
}
static class UuidHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
// Log the request details
String requestUri = exchange.getRequestURI().toString();
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("Received request for " + requestUri + " at " + timestamp);
// Generate a UUID
String response = UUID.randomUUID().toString();
// Send the response headers (200 OK and the length of the response)
exchange.sendResponseHeaders(200, response.length());
// Write the response body
OutputStream os = exchange.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