Is there any good open-source Java library for creating a HTTP server? I am looking for this.
I want it to be able to run on Java SE 8, without requiring Java EE. And, I want it to support “graceful stop”, that is, when I call this “graceful stop” method, the HTTP server stops accepting new HTTP requests, but continue processing existing HTTP requests, and waits indefinitely until all existing HTTP requests have been processed. There shouldn’t be a max time for this waiting, because I may want to wait as long as all existing HTTP requests have been processed. If I don’t want to wait, I may simply stop the program process forcefully.
This library does not need to support HTTPS, because I plan to deploy this server in a trusted internal network.
I want to use this library like this (in this example, the imaginary “somehttpserver” package is provided by the HTTP server library):
import somehttpserver.HttpServer;
import somehttpserver.HttpMethod;
import java.util.Scanner;
public class MyHttpServerProgram {
public static void main(String[] args) {
HttpServer theHttpServer;
boolean isSuccess;
Scanner consoleScanner;
String consoleInput;
theHttpServer = new HttpServer();
theHttpServer.setListeningPort(9000);
//add HTTP "endpoints", which are combinations of a HTTP method and a URL
//the handlers are objects implementing the interface somehttpserver.HttpEndpointHandler
theHttpServer.addEndpoint(HttpMethod.POST, "/postSomething", new MyHandler1());
theHttpServer.addEndpoint(HttpMethod.GET, "/getSomething", new MyHandler2());
//add more HTTP endpoints...
//start the HTTP server
isSuccess = true;
try {
theHttpServer.start();
} catch (Exception e) {
isSuccess = false;
}
if (isSuccess == false) {
System.out.print("The HTTP server has failed to start.");
} else {
//Now the HTTP server has started successfully.
//The HTTP server runs concurrently, that is, runs in its own thread, not in this thread.
System.out.print("The HTTP server has started successfully.");
System.out.print("nn");
System.out.print("When you want to stop this HTTP server, enter STOP to stop it.n");
consoleScanner = new Scanner(System.in);
consoleInput = consoleScanner.nextLine();
while ((consoleInput.equals("STOP")) == false) {
consoleInput = consoleScanner.nextLine();
}
//Now, we stop the HTTP server
//Stop the HTTP server in a graceful way, that is:
//stop accepting new HTTP requests, but continue processing existing HTTP requests, and wait indefinitely until all existing HTTP requests have been processed
theHttpServer.stop();
System.out.print("n");
System.out.print("The HTTP server has stopped successfully.");
}
System.out.print("nn");
System.out.print("The HTTP server program will exit. Enter OK to exit.n");
consoleInput = consoleScanner.nextLine();
while ((consoleInput.equals("OK")) == false) {
consoleInput = consoleScanner.nextLine();
}
}
}
Is there any such library?