A Simple HTTP Server in Java

Do you want to implement an HTTP server, but do you not want to take any risk of writing a full-fledged HTTP server? Developing an HTTP server with full capability is not a trivial task. But Java has got a solution to this kind of problem. Java supports an in-built HTTP server. By just writing 100 lines of code, we can develop a somewhat-decent HTTP server that can handle HTTP GET and POST requests. We can also leverage it to handle other HTTP commands as well.

HTTPServer class

Java SDK provides an in-built server called HttpServer. This class belongs to com.sun.net   package. 

We can instantiate the server like this:

Java
 




xxxxxxxxxx
1


 
1
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8001), 0);



The above line creates an HTTPServer instance on localhost with port number 8001. But, there is one more argument with value 0. This value is used for back logging.


The Complete Java Coder Bundle.*

*Affiliate link. See Terms of Use.

Back Logging

When a server accepts a client request, this request first will be queued by the operating system. Later, it will be given to the server to process the request. All of these simultaneous requests will be queued by the operating system. However, the operating system will decide how many of these requests can be queued at any given point in time. This value represents back logging. In our example, this value is 0, which means that we do not queue any requests.


Server Code

We are going to develop the following HTTP server code:

Java
 




xxxxxxxxxx
1


 
1
server.createContext("/test", new  MyHttpHandler());
2
server.setExecutor(threadPoolExecutor);
3
server.start();
4
logger.info(" Server started on port 8001");



We created a context called, test. This is nothing but the context root of the application. The second parameter is a handler instance, which will handle the HTTP requests. We will look into this class shortly.

We can use a thread pool executor, along with this server instance. In our case, we created a thread pool with 10.

Java
 




xxxxxxxxxx
1


 
1
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newFixedThreadPool(10);



Next, we start the server:

Java
 




xxxxxxxxxx
1


 
1
server.start();



With just three to four lines of code, we created an HTTP server with a context root that listens on a port!

HTTPHandler Class

This is an interface with a method called handle(..). Let us take a look at our implementation of this interface.

Java
 




x
44


 
1
private class MyHttpHandler implements HttpHandler {    
2
  @Override    
3
  public void handle(HttpExchange httpExchange) throws IOException {
4
    String requestParamValue=null; 
5
    if("GET".equals(httpExchange.getRequestMethod())) { 
6
       requestParamValue = handleGetRequest(httpExchange);
7
     }else if("POST".equals(httpExchange)) { 
8
       requestParamValue = handlePostRequest(httpExchange);        
9
      }  
10
11
    handleResponse(httpExchange,requestParamValue); 
12
  }
13
14
   private String handleGetRequest(HttpExchange httpExchange) {
15
            return httpExchange.
16
                    getRequestURI()
17
                    .toString()
18
                    .split("\\?")[1]
19
                    .split("=")[1];
20
   }
21
22
   private void handleResponse(HttpExchange httpExchange, String requestParamValue)  throws  IOException {
23
            OutputStream outputStream = httpExchange.getResponseBody();
24
            StringBuilder htmlBuilder = new StringBuilder();
25
            
26
            htmlBuilder.append("<html>").
27
                    append("<body>").
28
                    append("<h1>").
29
                    append("Hello ")
30
                    .append(requestParamValue)
31
                    .append("</h1>")
32
                    .append("</body>")
33
                    .append("</html>");
34
35
       // encode HTML content 
36
       String htmlResponse = StringEscapeUtils.escapeHtml4(htmlBuilder.toString());
37
     
38
            // this line is a must
39
            httpExchange.sendResponseHeaders(200, htmlResponse.length());
40
41
            outputStream.write(htmlResponse.getBytes());
42
            outputStream.flush();
43
            outputStream.close();
44
        }
45
}



This is the code that handles the request and sends the response back to the client. The request and the response is handled by the HttpExchange class.

Handle GET Request

The GET request is handled by the handleGETRequest() method. This method, in turn, calls the getRequestURI() method of HttpExchange class to extract the request parameter value contained in the URI. This is a minimal method that will handle only one parameter present in the request. However, this can be modified to meet different requirements.

Handle Response

Finally, we are going to send our response back to the client. This is achieved by the handleResponse(..) method. In this method, we get the output stream by calling the getResponseBody() method of the HttpExchange class. Later, we can write HTML content to the output stream. 

The most important point is to send a response header  back to the client. If you miss it, you will get an error called  ERR_EMPTY_RESPONSE in the browser.

If all goes well, you can see the response in the browser for a request url:

http://localhost:8001/test?name=sam.


Further Reading

 

 

 

 

Top