Http Server in Java

Our first program will demonstrate how to create a basic HTTP server. Here’s the full source code:

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.Map;

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);
        server.start();
    }

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            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 {
            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());
            }
        }
    }
}

In Java, we use the com.sun.net.httpserver package to create a basic HTTP server. This package provides similar functionality to the net/http package.

A fundamental concept in Java HTTP servers is HttpHandler. It’s an interface that defines how to handle HTTP requests. We create handler classes that implement this interface.

The HelloHandler class is a simple handler that responds with “hello\n”. The HeadersHandler class reads all the HTTP request headers and echoes them into the response body.

In the main method, we create an HttpServer instance, set up the routes using createContext, and start the server. The server listens 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 set up a basic HTTP server in Java, define routes, and handle requests. The concepts are similar to other languages, but the implementation details are specific to Java and its HTTP server API.