Java HttpServer Example

Java HttpServer Example

In this example we are going to learn hpw to run HttpServer on local machine

com.sun.net.httpserver  provides Http Server API which can be used to build HTTP Server 
Before going to start check below classes


HttpServer
This is a class which implements HTTP Server. This calss as method create() to create instance of the class.
We need to bind the server to an IP Address and a Port number while initializing.


HttpContext
Class which represents a mapping between root URI path to a httpHandler.


HttpHandler
Interface which needs to be implemented by the application to handle the Http request 


HttpExchange
The Instance of this class is passed to HttpHandler class method handle(). This method will handle the input request and prepare and send output response.Let's check the code

public class BasicHttpServerExample {

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

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

Output

Java HttpServer

Accessing Request Information
 

public class HttpServerApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8001), 0);
            server.createContext("/test", new  MyHttpHandler());
            ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newFixedThreadPool(10);
                server.setExecutor(threadPoolExecutor);

                server.start();

                Logger.getLogger(" Server started on port 8001");
        } catch (IOException ex) {
            Logger.getLogger(HttpServerApp.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    static private class MyHttpHandler implements HttpHandler {    

  @Override    

  public void handle(HttpExchange httpExchange) throws IOException {

    String requestParamValue=null; 

    if("GET".equals(httpExchange.getRequestMethod())) { 

       requestParamValue = handleGetRequest(httpExchange);

     }else if("POST".equals(httpExchange)) { 

       //requestParamValue = handlePostRequest(httpExchange);        

      }  


    handleResponse(httpExchange,requestParamValue); 

  }


   private String handleGetRequest(HttpExchange httpExchange) {

            return httpExchange.

                    getRequestURI()

                    .toString()

                    .split("\\?")[1]

                    .split("=")[1];

   }


   private void handleResponse(HttpExchange httpExchange, String requestParamValue)  throws  IOException {

            OutputStream outputStream = httpExchange.getResponseBody();

            StringBuilder htmlBuilder = new StringBuilder();

            

            htmlBuilder.append("<html>").

                    append("<body>").

                    append("<h1>").

                    append("Hello ")

                    .append(requestParamValue)

                    .append("</h1>")

                    .append("</body>")

                    .append("</html>")

// encode HTML content 

            String htmlResponse = StringEscapeUtils.escapeHtml4(htmlBuilder.toString());

     

            // this line is a must

            httpExchange.sendResponseHeaders(200, htmlResponse.length());


            outputStream.write(htmlResponse.getBytes());

            outputStream.flush();

            outputStream.close();

        }

}
}


 

output 
open in broser 
http://localhost:8001/test?name=chandu