A Built-In Java HttpServer 📎
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 = "duke";
HttpServer server = HttpServer.create(new InetSocketAddress(4250), 0);
HttpContext context = server.createContext("/java");
context.setHandler((he) -> {
he.sendResponseHeaders(200, payload.getBytes().length);
final OutputStream output = he.getResponseBody();
output.write(payload.getBytes());
output.flush();
he.close();
});
server.start();
Test:
curl -i http://localhost:4250/java
returns:
HTTP/1.1 200 OK
Date: Thu, 09 Jul 2015 02:48:37 GMT
Content-length: 4
duke%
Warning: The packages com.sun.*
are not part of the supported, public interface and may even disappear in upcoming Java releases.