{{announcement.body}}
{{announcement.title}}

A Simple HTTP Server in Java

DZone 's Guide to

A Simple HTTP Server in Java

In this article, we discuss how to create a simple HTTP server in Java that can handle GET and POST requests with Java SDK's HttpServer class.

· Java Zone ·
Free Resource

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.

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.

You may also like: Programming Models for Servers in Java.

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


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

Topics:
java ,java 8 ,server ,html ,protocol ,get ,post ,backend ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}