Close

Java - HttpServer Example

[Last Updated: May 11, 2018]

The package com.sun.net.httpserver provides Http server API, which can be used to build embedded HTTP servers. To get started with this API, we need to get familiar with the following classes:

  • HttpServer

    This class implements a simple HTTP server. It has factory methods create() to create its instance. We need to bind the server to an IP address and port number while initializing.

  • HttpContext

    It represents a mapping between the root URI path to a HttpHandler.

  • HttpHandler

    It is an interface, which needs to be implemented by the application to handle the Http requests. It has only one method:
    void handle(HttpExchange exchange) throws IOException


  • HttpExchange

    An instance of this class is passed to HttpHandler#handle(). It has methods to access Http request information, and to prepare and send the response.

Example

This is a very simple example to create the HttpServer:

public class BasicHttpServerExample {

  public static void main(String[] args) throws IOException {
      HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
      HttpContext context = server.createContext("/");
      context.setHandler(BasicHttpServerExample::handleRequest);
      server.start();
  }

  private static void handleRequest(HttpExchange exchange) throws IOException {
      String response = "Hi there!";
      exchange.sendResponseHeaders(200, response.getBytes().length);//response code and length
      OutputStream os = exchange.getResponseBody();
      os.write(response.getBytes());
      os.close();
  }
}

Output

Running the above main class and accessing the application in the browser:

Accessing Request Information

public class BasicHttpServerExample2 {

  public static void main(String[] args) throws IOException {
      HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
      HttpContext context = server.createContext("/example");
      context.setHandler(BasicHttpServerExample2::handleRequest);
      server.start();
  }

  private static void handleRequest(HttpExchange exchange) throws IOException {
      URI requestURI = exchange.getRequestURI();
      printRequestInfo(exchange);
      String response = "This is the response at " + requestURI;
      exchange.sendResponseHeaders(200, response.getBytes().length);
      OutputStream os = exchange.getResponseBody();
      os.write(response.getBytes());
      os.close();
  }

  private static void printRequestInfo(HttpExchange exchange) {
      System.out.println("-- headers --");
      Headers requestHeaders = exchange.getRequestHeaders();
      requestHeaders.entrySet().forEach(System.out::println);

      System.out.println("-- principle --");
      HttpPrincipal principal = exchange.getPrincipal();
      System.out.println(principal);

      System.out.println("-- HTTP method --");
      String requestMethod = exchange.getRequestMethod();
      System.out.println(requestMethod);

      System.out.println("-- query --");
      URI requestURI = exchange.getRequestURI();
      String query = requestURI.getQuery();
      System.out.println(query);
  }
}

Output

On the server console:

-- headers --
Accept-encoding=[gzip, deflate, br]
Cookie=[Idea-d72f48cc=a1722887-bfad-47cd-b8b3-df88f97951e3]
Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8]
Connection=[keep-alive]
Host=[localhost:8500]
User-agent=[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36]
Accept-language=[en-US,en;q=0.9]
Upgrade-insecure-requests=[1]
-- principle --
null
-- HTTP method --
GET
-- query --
x=1&y=2

Example Project

Dependencies and Technologies Used:

  • JDK 10
  • Maven 3.3.9

Java - HttpServer Example Select All Download
  • java-http-server-basic-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • BasicHttpServerExample.java

    See Also