HTTP Server using JAVA

Java is the object oriented programming language which provides lots of exciting features. Here i am come up with a sample program to create HTTP server with java .

With below mentioned program can able set up a HTTP server and get current time with a server. After developing this script it can be wrap as JAR or test with IDE like eclipse.

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

public class SimpleServer {
  static int port = 5010;
  public static void main(String[] args) throws IOException {   
  InetSocketAddress socket = new InetSocketAddress("0.0.0.0", port);
      HttpServer server = HttpServer.create();
      server.bind(socket, port);
      System.out.println("server started at " + port);
      HttpContext rootContext = server.createContext("/");
      HttpContext timeContext = server.createContext("/gettime");
      rootContext.setHandler(SimpleServer::RootHandler);
      timeContext.setHandler(SimpleServer::TimeHandler);
      server.start();
  }
  
  public static void RootHandler(HttpExchange he) throws IOException {
      String response = "<h1>Server start success if you see this          message</h1>" + "<h1>Port: " + port + "</h1>";
      he.sendResponseHeaders(200, response.length());
      OutputStream os = he.getResponseBody();
      os.write(response.getBytes());
      os.close();
  }  
  
  public static void TimeHandler(HttpExchange he) throws IOException {
      Date date = new Date();
      String strDateFormat = "dd-MM-yyyy hh:mm:ss a";
      DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
      String formattedDate= dateFormat.format(date);
      
      String response = "<h1>Current time is...</h1>" + "<h2>" + formattedDate + "</h2>";
      he.sendResponseHeaders(200, response.length());
      OutputStream os = he.getResponseBody();
      os.write(response.getBytes());
      os.close();
  } 
}

After running this program, while running http://localhost:5010/ link on browser can able to get a response "Server start success if you see this message Port: 5010".

http://localhost:5010/
http://localhost:5010/gettime

And running http://localhost:5010/gettime link can able to get response"Current time of the server system".

Here response is String format able construct different data format if required.

Comments