Home » Core Java » sun » net » httpserver » HttpServer » com.sun.net.httpserver.HttpServer Example

About Ashraf Sarhan

Avatar photo
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.

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.


  • 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.


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
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
		} catch (IOException e) {


	 * Start.
	public void start() {



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.


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
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();
	 * 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.


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
		System.out.println("Server is started and listening on port "+ PORT);



  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.

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

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

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
3 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.