Easiest way to create a built-in Java HTTP Server
Introduced in JDK 1.6, com.sun.net.httpserver package enables implementation of embedded HTTP servers. Oracle official Javadoc tells the following : “Provides a simple high-level HTTP server API, which can be used to build embedded HTTP servers”.
However, it’s important to consider that com.sun.* packages are not part of the supported, public interface and may even disappear in upcoming Java releases. There is a dedicated FAQ entry about the question on Oracle site : http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html .
But for fun, you can use this API to create built-in embedded HTTP Server in Java with no dependencies. Entry point is class com.sun.net.httpserver.HttpServer which must be created and then HttpContext that will let you to define context to handle requests.
Here, we define context on /myapp to handle requests with following code :
import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; // ... String payload = "Hello from my built-in server !"; HttpServer server = HttpServer.create(new InetSocketAddress(4250), 0); HttpContext context = server.createContext("/myapp"); context.setHandler((he) -> { he.sendResponseHeaders(200, payload.getBytes().length); final OutputStream output = he.getResponseBody(); output.write(payload.getBytes()); output.flush(); he.close(); }); server.start();
To test our built-in HTTP server, we can use curl with the following request :
curl -i http://localhost:4250/myapp
It will return the following result :
HTTP/1.1 200 OK Date: Thu, 16 Jul 2015 19:48:30 GMT Content-length: 31 Hello from my built-in server !
Leave a Reply
You must be logged in to post a comment.