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 { private static void handleRequest(HttpExchange exchange) throws IOException { |
Output
Accessing Request Information
public class HttpServerApp { /** server.start(); Logger.getLogger(" Server started on port 8001"); @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); }
}
return httpExchange. getRequestURI() .toString() .split("\\?")[1] .split("=")[1]; }
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.flush(); outputStream.close(); } } |
output
open in broser
http://localhost:8001/test?name=chandu