Java
HTTP Server
Java SE API
Programming
Web Development

Simple HTTP server in Java using only Java SE API

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Creating a simple HTTP server in Java using only the standard Java SE API can provide lightweight web services without needing additional libraries such as Spring or Jakarta EE. This is especially useful for testing, prototyping, or for when you need a simple backend for an application without the overhead of deploying an entire application server.

Java HTTPServer Class Overview

The core class utilized for this purpose in Java is the HttpServer provided by the com.sun.net.httpserver package, which was introduced in Java 6. This package isn't part of the Java standard, but Oracle includes it in its JDK. It's important to note that this server is very basic and is suitable for handling low to moderate load environments.

Creating a Simple HTTP Server

The process of setting up a basic server involves several steps:

  1. Instantiate the Server: Create an instance of HttpServer.
  2. Create Contexts: Define context objects which handle the routing of incoming requests.
  3. Start the Server: Start the server so it begins listening to incoming client requests.

Here is a simple example to demonstrate how this can be done:

java
1import com.sun.net.httpserver.HttpServer;
2import com.sun.net.httpserver.HttpHandler;
3import com.sun.net.httpserver.HttpExchange;
4import java.io.IOException;
5import java.io.OutputStream;
6import java.net.InetSocketAddress;
7
8public class SimpleHttpServer {
9    public static void main(String[] args) throws IOException {
10        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
11        server.createContext("/test", new MyHandler());
12        server.setExecutor(null); // creates a default executor
13        server.start();
14        System.out.println("Server started at " + server.getAddress());
15    }
16
17    static class MyHandler implements HttpHandler {
18        public void handle(HttpExchange exchange) throws IOException {
19            String response = "This is the response";
20            exchange.sendResponseHeaders(200, response.getBytes().length);
21            OutputStream os = exchange.getResponseBody();
22            os.write(response.getBytes());
23            os.close();
24        }
25    }
26}

In this basic example, the server listens on port 8000 and responds to HTTP requests at the /test route by returning a plain text response.

Request Handling

Each request is handled by an implementation of the HttpHandler interface, which provides a single method handle, equipped with an HttpExchange object. The HttpExchange object encapsulates a request received and a response to be generated. You can do more complex request handling, including parsing request headers and returning various types of responses.

Custom Executing

By default, the server uses a system-built executor – this means it handles requests using a default execution strategy which is suitable for a small number of concurrent connections. However, you can set a custom executor to improve the concurrency and performance of your server like this:

java
server.setExecutor(Executors.newFixedThreadPool(10));

Summary Table

The table below summarizes the key components of setting up a HttpServer:

ComponentRole in Server Setup
HttpServerServer instance which listens for connections
InetSocketAddressBinds server to a specific port
HttpHandlerHandles the specifics of each routed request
HttpExchangeManages data about an HTTP exchange (request/response)

Limitations

Though Java's built-in HTTP server is functional for simple scenarios, it lacks many features necessary for full-fledged web applications, such as advanced routing, complex error handling, and integrated security features. For more sophisticated requirements, consider using more robust solutions.

Conclusion

Using Java SE's API for building an HTTP server can be incredibly handy for small-scale projects and learning purposes. This approach provides an accessible means to understand the basics of web server operations, HTTP protocol, and handling with pure Java. For more robust application needs, considering external libraries or a complete application framework would be beneficial.


Course illustration
Course illustration

All Rights Reserved.