Http Server in Karel
Here’s the translation of the HTTP Server example from Go to Java, formatted in Markdown for Hugo:
Our HTTP server example demonstrates how to create a basic server using Java’s built-in com.sun.net.httpserver
package.
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;
import java.util.Map;
public class HttpServerExample {
// A fundamental concept in HTTP servers is handlers. In Java, we can create
// handlers by implementing the HttpHandler interface.
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
// The handle method is where we write our response. Here, our simple
// response is just "hello\n".
String response = "hello\n";
exchange.sendResponseHeaders(200, response.length());
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
}
}
}
static class HeadersHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
// This handler does something a little more sophisticated by reading
// all the HTTP request headers and echoing them into the response body.
StringBuilder response = new StringBuilder();
for (Map.Entry<String, java.util.List<String>> entry : exchange.getRequestHeaders().entrySet()) {
for (String value : entry.getValue()) {
response.append(entry.getKey()).append(": ").append(value).append("\n");
}
}
exchange.sendResponseHeaders(200, response.length());
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.toString().getBytes());
}
}
}
public static void main(String[] args) throws IOException {
// Create an HTTP server that listens on port 8090
HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
// We register our handlers on server contexts
server.createContext("/hello", new HelloHandler());
server.createContext("/headers", new HeadersHandler());
// Start the server
server.start();
System.out.println("Server is listening on port 8090");
}
}
To run the server:
$ javac HttpServerExample.java
$ java HttpServerExample &
Access the /hello
route:
$ curl localhost:8090/hello
hello
This example demonstrates how to create a basic HTTP server in Java. It uses the com.sun.net.httpserver
package, which is included in the JDK.
The HelloHandler
and HeadersHandler
classes implement the HttpHandler
interface, defining how to respond to requests to the /hello
and /headers
routes respectively.
In the main
method, we create an HttpServer
instance, set up the context paths with their corresponding handlers, and start the server.
Note that this is a simple example and may not be suitable for production use. For more robust server applications, you might want to consider using frameworks like Spring Boot or Java EE.