HttpServer

com.sun.net.httpserver.HttpServer Example

In this example we shall show you how to make use of HttpServer class, This class implements a simple HTTP server where we can start an embedded HTTP server which is bound to an IP address and port number and listens for incoming TCP connections from clients on this address.

To process the incoming requests, we have to implement one or more HttpHandler objects which must be associated with the HttpServer.

Also, we have to register HttpHandler with a root URI path which represents the location of the application or service on the HttpServer by calling createContext(String,HttpHandler) of the HttpServer to map specific handler to the HttpServer.

Tip

  • Any request for which no handler can be found is rejected with a 404 response.
  • Management of threads can be done by providing a Executor object for the HttpServer. If null is provided a default implementation is used.

Now, suppose that you want to write a web application in Java and you prefer to create a self-contained simple HttpServer solution other than a Servlet based web application. The typical scenario which should be followed contains the following steps:

  1. Construct an HttpServer object.
  2. Create one or more HttpHandler to process the incoming requests.
  3. Attach one or more HttpHandler objects to the HttpServer object then start it.

Let’s see the below example, we create a new web application where the user can send a request with two parameters (first name, last name) then the server send a response which contains Hello, Full Name back to the user.

1. Example

SimpleHttpServer class has a constructor which takes three given parameters (int port, String contextHttpHandler handler) and returns a new SimpleHttpServer. Also, it contains start() which allows to start the newly created HttpServer.

SimpleHttpServer.java:

package com.jcg;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * @author ashraf
 * 
 */
@SuppressWarnings("restriction")
public class SimpleHttpServer {

	private HttpServer httpServer;

	/**
	 * Instantiates a new simple http server.
	 *
	 * @param port the port
	 * @param context the context
	 * @param handler the handler
	 */
	public SimpleHttpServer(int port, String context, HttpHandler handler) {
		try {
			//Create HttpServer which is listening on the given port 
			httpServer = HttpServer.create(new InetSocketAddress(port), 0);
			//Create a new context for the given context and handler
			httpServer.createContext(context, handler);
			//Create a default executor
			httpServer.setExecutor(null);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Start.
	 */
	public void start() {
		this.httpServer.start();
	}

}

Tip

httpServer = HttpServer.create(new InetSocketAddress(port), 0);

  • The first argument is InetSocketAddress(int port) which creates a socket address where the IP address is the wildcard address and the port number a specified value which are localhost:8000 in our example.
  • The second argument is the backlog of outstanding connections that the operating system should queue while they are waiting to be accepted by the server process. If set to zero then a default value is used, which should be suitable for most purposes.

HttpRequestHandler class contains the logic to process all the incoming requests, it takes the request URI query parameters (fName, lName), builds the response and returns it back to the user.

HttpRequestHandler.java:

package com.jcg;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author ashraf
 *
 */
@SuppressWarnings("restriction")
public class HttpRequestHandler implements HttpHandler {
	
	private static final String F_NAME = "fname";
	private static final String L_NAME = "lname";
	
	private static final int PARAM_NAME_IDX = 0;
	private static final int PARAM_VALUE_IDX = 1;
	
	private static final int HTTP_OK_STATUS = 200;
	
	private static final String AND_DELIMITER = "&";
	private static final String EQUAL_DELIMITER = "=";
	
	public void handle(HttpExchange t) throws IOException {

		//Create a response form the request query parameters
		URI uri = t.getRequestURI();
		String response = createResponseFromQueryParams(uri);
		System.out.println("Response: " + response);
		//Set the response header status and length
		t.sendResponseHeaders(HTTP_OK_STATUS, response.getBytes().length);
		//Write the response string
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
	}
	
	/**
	 * Creates the response from query params.
	 *
	 * @param uri the uri
	 * @return the string
	 */
	private String createResponseFromQueryParams(URI uri) {
		
		String fName = "";
		String lName = "";
		//Get the request query
		String query = uri.getQuery();
		if (query != null) {
			System.out.println("Query: " + query);
			String[] queryParams = query.split(AND_DELIMITER);
			if (queryParams.length > 0) {
				for (String qParam : queryParams) {
					String[] param = qParam.split(EQUAL_DELIMITER);
					if (param.length > 0) {
						for (int i = 0; i < param.length; i++) {
							if (F_NAME.equalsIgnoreCase(param[PARAM_NAME_IDX])) {
								fName = param[PARAM_VALUE_IDX];
							}
							if (L_NAME.equalsIgnoreCase(param[PARAM_NAME_IDX])) {
								lName = param[PARAM_VALUE_IDX];
							}
						}
					}
				}
			}
		}
		
		return "Hello, " + fName + " " + lName;
	}
}

HttpServerTest creates a new HttpServer then it calls the start() method to start the HttpServer. Now, we can go to our browser, hit this url http://localhost:8000/app?fName=Ashraf&lName=Sarhan and see the response.

HttpServerTest.java:

package com.jcg;

/**
 * @author ashraf
 * 
 */
public class HttpServerTest {

	private static final String CONTEXT = "/app";
	private static final int PORT = 8000;

	public static void main(String[] args) throws Exception {

		// Create a new SimpleHttpServer
		SimpleHttpServer simpleHttpServer = new SimpleHttpServer(PORT, CONTEXT,
				new HttpRequestHandler());

		// Start the server
		simpleHttpServer.start();
		System.out.println("Server is started and listening on port "+ PORT);
	}

}

Output:

  1. Console:
    Server is started and listening on port 8000
    Query: fName=Ashraf&lName=Sarhan
    Response: Hello, Ashraf Sarhan
    
  2. Browser:
    Figure 1: Http Demo
    Figure 1: Http Demo

Download the Source Code

This was an example of HttpServer class.

Download
You can download the full source code of this example here: HttpServerExampleCode.zip

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Saud
Saud
5 years ago

Hi, thanks for this very handy tutorial! I wanted to apologise for accidentally down voting the article, I intended to up vote but the website is not allowing me to change my choice.

Back to top button