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 theHttpServer
. Ifnull
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:
- Construct an
HttpServer
object. - Create one or more
HttpHandler
to process the incoming requests. - Attach one or more
HttpHandler
objects to theHttpServer
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 context
, HttpHandler 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 arelocalhost: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:
- Console:
Server is started and listening on port 8000 Query: fName=Ashraf&lName=Sarhan Response: Hello, Ashraf Sarhan
- Browser:
Download the Source Code
This was an example of HttpServer
class.
You can download the full source code of this example here: HttpServerExampleCode.zip
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.