Create Simple HTTP Server in Java
In this example, We will show you about, How to create simple http server in Java. The example has been tested with environment and output is shared in the same post.
We have lots of famous servers(HTTP) such as Tomcat, JBoss, and etc.. So is it possible for us to create simple HTTP server in java? Yes we can able to do it. lets create our own simple http server in java with following step by step procedures.
1) Project Structure
Note: You can able to find rt.jar file inside the folder of JRE installed (ie: {JAVA_HOME}\jdk\jre\lib\rt.jar) on your machine. Once you found that add the jar file to lib folder of your project and set the classpath using eclipse tool or through command line.
2) Creating Server and Request Handler
package com.dineshkrish; import java.io.IOException; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class MyServer { private int port; private HttpServer server = null; public MyServer(int port) { this.port = port; } // Method to initialize the server public void init() { try { InetSocketAddress address = new InetSocketAddress(port); server = HttpServer.create(address, 0); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } // Method to deploying the application public void deployApplication(String contextPath, HttpHandler handler) { if ((contextPath != null && !contextPath.isEmpty()) && handler != null) { server.createContext(contextPath, handler); } else { System.out.println("Invalid Information Provided"); } } // Method to start the server public void start() { server.start(); System.out.println("Server is running...."); } }
package com.dineshkrish; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; public class MyRequestHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { URI requestedURI = httpExchange.getRequestURI(); if (requestedURI != null) { sendResponse(requestedURI, httpExchange); } } private void sendResponse(URI requestedURI, HttpExchange httpExchange) { if (requestedURI != null) { try { String path = String.valueOf(requestedURI); String response = ""; if (path != null && !path.isEmpty()) { if ("/welcome".equals(path)) { response = getResponse(path); } else if ("/welcome/page1".equals(path)) { response = getResponse(path); } else if ("/welcome/page2".equals(path)) { response = getResponse(path); } else if ("/welcome/page3".equals(path)) { response = getResponse(path); } else { response = "<h1>Oops!!! Page not found...</h1>"; } } httpExchange.sendResponseHeaders(200, response.length()); OutputStream os = httpExchange.getResponseBody(); os.write(response.getBytes()); os.close(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } private String getResponse(String requestURL) { String fileName = requestMapping().get(requestURL); File file = new File(fileName); String content = ""; try { byte[] b = Files.readAllBytes(file.toPath()); content = new String(b); } catch (IOException e) { e.printStackTrace(); } return content; } private Map<String, String> requestMapping() { Map<String, String> map = new HashMap<String, String>(); map.put("/welcome", "pages/welcome.html"); map.put("/welcome/page1", "pages/page1.html"); map.put("/welcome/page2", "pages/page2.html"); map.put("/welcome/page3", "pages/page3.html"); return map; } }
3) Response Pages
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Welcome</title> </head> <body> <h1>Welcome to an application</h1> <ul> <li><a href="/welcome/page1">Page 1</a></li> <li><a href="/welcome/page2">Page 2</a></li> <li><a href="/welcome/page3">Page 3</a></li> </ul> <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. </p> <hr> <p>powered by <a href="https://idineshkrishnan.com" target="_blank">www.dineshkrish.com</a></p> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Page 1</title> </head> <body> <h1>Welcome to an application</h1> <h4>Page 1 Content</h4> <a href="/welcome">Go Back to Main Page</a> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Page 2</title> </head> <body> <h1>Welcome to an application</h1> <h4>Page 2 Content</h4> <a href="/welcome">Go Back to Main Page</a> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Page 3</title> </head> <body> <h1>Welcome to an application</h1> <h4>Page 3 Content</h4> <a href="/welcome">Go Back to Main Page</a> </body> </html>
4) Publishing the Server
package com.dineshkrish; public class Publisher { public static void main(String[] args) { MyServer applicationServer = new MyServer(8000); applicationServer.init(); applicationServer.deployApplication("/welcome", new MyRequestHandler()); applicationServer.start(); } }
5) Download Source Code
You can able to download the entire example source code here
Output
The following output will give you idea about, How to create simple http server in java.
References
1. Java™ HTTP Server Documentation
2. Java HttpServer API
3. Java HttpExchage API
4. Java Httphandler API
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet