19 Nov, 2024
Repository link: https://github.com/ProgrammerPratik/HTTP-server-implementation
This project is a simple yet robust HTTP server using Java to handle basic HTTP requests and serve predefined routes. The server supports multithreading, allowing it to handle multiple client connections simultaneously. It's an excellent project for understanding the basics of HTTP, server programming, and multithreading in Java.
/
: A welcoming page with the current date and time./time
: Returns the current time in JSON format./health
: Reports the server's health status./stats
: Displays basic server statistics like active threads and available memory.404 Not Found
response.1. Clone the Repository
git clone https://github.com/ProgrammerPratik/HTTP-server-implementation.git
cd SimpleHttpServer
2. Compile and run the Server
javac SimpleHttpServer.java
java SimpleHttpServer
3. Accessing the Server through your browser
just visit: http://localhost:8080/ OR http://127.0.0.1:8080/ for locally accessing the server you ran (by default the server will run on port 8080)
You can also check the data sent by the user on the server side. This includes the headers and other details from the HTTP request such as User-Agent, Accept, and more as shown below:
The server provides a simple interface to add custom routes. Here’s an example:
server.addRoute("/hello", (request) ->
{
return new HttpResponse(200, "<h1>Hello, World!</h1>");
}
After adding this code, the route "/hello" will serve a basic HTML response.
Request: curl http://localhost:8080/time
Response:
{"time": "2024-11-19T19:15:45.9178453"}
Request: curl http://localhost:8080/health
Response:
{"status": "healthy", "uptime": "1732023983004"}
I also wrote an article on how you can implement simpler HTTP server using Java which explains how basics work incase you are curious.
Article link: https://programmerpratik.github.io/articles/http-using-java.html