Develop an HTTP Server in Java

Sayan Paul
3 min readFeb 5, 2022

--

Photo by Gabriel Heinzer on Unsplash

A lot of the World Wide Web is developed on the Client-Server model. According to this structure, a task or workload is divided into two parts; a service or a resource provider, called a server, and a requester who wants to utilize the resource or the service, called a client.

On the internet, there are many different protocols that are being used. A protocol is basically a set of instructions that two machines (or software) need to follow in order to communicate. For a Client to send a request to a server and for the server to understand it, they must follow the same protocol(s). In our example I would be demonstrating the Hyper Text Transfer Protocol (HTTP).

Java has an HTTPServer class under the package com.sun.net.httpserver . We will create an object of this class, and then assign a port for the server to run on. A port is a virtual end-point within the operating system from where a network connection can start or end. Since our server has to establish communication with clients, it needs to be run on a port. We can use the class InetSocketAddress under the package java.net for this purpose.

private static void runServer() throws IOException{
// Create a server that runs on the port 8000
HttpServer server = HttpServerImpl.create(new
InetSocketAddress(8000),0);
}

When a request is received at the server, an instance of the HTTPContext class is created. A Context describes all the HTTP-specific information about a single HTTP request.

Each HTTPContext has a path and an HTTP Request Handler. There are different types of requests that a client can make to a server. The Request Handler takes care of what needs to be done when a request is received at the server. We need to implement the HTTPHandler interface. Whenever a request is sent to the Server, the handle() method of the class that implements this interface is called. We can say that what happens at the server has to be defined in this method.

private static void runServer() throws IOException{
HttpServer server = HttpServerImpl.create(new
InetSocketAddress(8000),0);
//Create an HTTP Context and set it's path
HttpContext context = server.createContext("/");

//Create a Request Handler for the Server
context.setHandler(new RequestHandler());
}
class RequestHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException{
//Code for what happens at the server, here we simply print
//the request message
InputStream inStream = httpExchange.getRequestBody();
Scanner scanner = new Scanner(inStream);
String data = scanner.nextLine();
System.out.println(data);
}
}

Every HTTP request has certain fields, that contain the information about it, like the time of arrival, the protocol used and many more along with a request body that contains some data. There are different kinds of requests like GET, POST, PUT etc. Once the request is received and processed, a response is sent back to the client, which contains all the data that it requested for. The HTTPExchange class contains all the data of the request that is received and the data of the response that would be sent back.

After setting up the Request Handler, use the method start() of HTTPServer to start running your server on the port.

Here’s the full code for making the sever :

public class Server {
private class RequestHandler {
@Override
public void handle(HttpExchange httpExchange) throws
IOException{
InputStream inStream = httpExchange.getRequestBody();
Scanner scanner = new Scanner(inStream);
String data = scanner.nextLine();
System.out.println(data);
}
}
private void runServer() throws IOException {
HttpServer server = HttpServerImpl.create(new
InetSocketAddress(8000),0);
HttpContext context = server.createContext("/");
context.setHandler(new RequestHandler());
server.start();
}


public static void main(String[] args){
try {
Server server = new Server();
server.runServer();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Check out my next post about making a server, Types of HTTP Request Methods .

--

--

Sayan Paul

It is believed that the ability to narrate stories sets us apart from other living beings.