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:
xxxxxxxxxx
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:
xxxxxxxxxx
server.createContext("/test", new MyHttpHandler());
server.setExecutor(threadPoolExecutor);
server.start();
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.
xxxxxxxxxx
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newFixedThreadPool(10);
Next, we start the server:
xxxxxxxxxx
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.
private class MyHttpHandler implements HttpHandler {
public void handle(HttpExchange httpExchange) throws IOException {
String requestParamValue=null;
if("GET".equals(httpExchange.getRequestMethod())) {
requestParamValue = handleGetRequest(httpExchange);
}else if("POST".equals(httpExchange)) {
requestParamValue = handlePostRequest(httpExchange);
}
handleResponse(httpExchange,requestParamValue);
}
private String handleGetRequest(HttpExchange httpExchange) {
return httpExchange.
getRequestURI()
.toString()
.split("\\?")[1]
.split("=")[1];
}
private void handleResponse(HttpExchange httpExchange, String requestParamValue) throws IOException {
OutputStream outputStream = httpExchange.getResponseBody();
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<html>").
append("<body>").
append("<h1>").
append("Hello ")
.append(requestParamValue)
.append("</h1>")
.append("</body>")
.append("</html>");
// encode HTML content
String htmlResponse = StringEscapeUtils.escapeHtml4(htmlBuilder.toString());
// this line is a must
httpExchange.sendResponseHeaders(200, htmlResponse.length());
outputStream.write(htmlResponse.getBytes());
outputStream.flush();
outputStream.close();
}
}
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
- Lightweight Embedded Java REST Server Without a Framework.
- Create and Publish Your Rest API Using Spring Boot and Heroku.
- Build a Spring Boot App With Secure Server-to-Server Communication Via OAuth 2.0.