Http Server in Minitab
Here’s the translation of the HTTP Server example from Go to Java, formatted in Markdown suitable 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;
public class HttpServerExample {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
server.createContext("/hello", new HelloHandler());
server.createContext("/headers", new HeadersHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "hello\n";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class HeadersHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
StringBuilder response = new StringBuilder();
t.getRequestHeaders().forEach((key, values) -> {
values.forEach(value -> response.append(key).append(": ").append(value).append("\n"));
});
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
}
In Java, we use the HttpServer
class from the com.sun.net.httpserver
package to create a basic HTTP server. This is similar to using the net/http
package in other languages.
A fundamental concept in Java HTTP servers is the HttpHandler
interface. This is analogous to handlers in other web frameworks. We implement this interface to define how our server should respond to different requests.
We define two handler classes: HelloHandler
and HeadersHandler
. Each implements the handle
method of the HttpHandler
interface.
The HelloHandler
simply responds with “hello\n” to any request.
The HeadersHandler
is more sophisticated. It reads all the HTTP request headers and echoes them into the response body.
In the main
method, we create the server, set up the routes (contexts in Java terminology), and start the server:
- We create the server to listen on port 8090.
- We register our handlers on server routes using the
createContext
method. - Finally, we call the
start
method to begin accepting incoming connections.
To run the server:
$ javac HttpServerExample.java
$ java HttpServerExample &
You can then access the server:
$ curl localhost:8090/hello
hello
This example demonstrates how to set up a basic HTTP server in Java, define custom handlers for different routes, and handle incoming requests.
Minitab: Python